In the below code I am trying to set some values for google map's lat long, when I call the change function which is bound to ng-click directive, the page doesn't load, but without change() func everything loads pretty well. I might be missing some core concepts of angular that is because I have started working on it just 10 days before, kindly correct me here and if someone can suggest me another way to change my lat long with button click, I will be really thankful for that suggestion.
app.controller('MapCtrl', function ($scope){
// $scope.change=function(){
$scope.Latitude="23.200000";
$scope.Longitude="79.225487";
$scope.assignLat=function () {
var lati= $scope.Latitude;
return lati;
}
$scope.assignLong=function () {
var longi= $scope.Longitude;
return longi;
}
console.log($scope.assignLat());
console.log($scope.assignLong());
// }
var cities = [{
city : 'India',
desc : 'This is the best country in the world!',
lat : $scope.assignLat(),
long : $scope.assignLong()
}];
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25,80),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
for (i = 0; i < cities.length; i++){
createMarker(cities[i]);
}
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
Related
I am using angularjs for my application.I am trying to load the address from user_address table in database and display it on map on load.
Here is the script i am using to load google maps
<script async defer src="https://maps.googleapis.com/maps/api/js?
key=myKey&callback=initMap">
</script>
Here is the html
<div id="map"></div>
<div id="repeatmap" data-ng-repeat="marker in markers | orderBy :
'title'">
<a id="country_container" href="#" ng-
click="openInfoWindow($event, marker)">
<label id="namesformap" >{{marker.title}}</label></a>
</div>
Here is the Controller.js
var DirectoryController = function($scope, $rootScope, $http,
$location, $route,DirectoryService,HomeService,$routeParams)
{
$scope.getAllCities = function()
{
DirectoryService.getAllCities().then(function(response){
$scope.cities = response.data;
console.log($scope.cities);
})
}
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25,80),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'),
mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc +
'</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' +
marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
for (var i = 0; i < $scope.cities.length; i++){
createMarker($scope.cities[i]);
}
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
}
In getAllCities function i am getting response from database that is all the names of cities.
As you can see in console i am able to get the response from database but i am not able to get $scope.cities value to for loop.It is saying Cannot read property 'length' of undefined.Can anyone tell how can i get value of $scope.cities into for loop so that in map i can display the cities returned from database.Now i am able to display map but with no cities and no markers.I dont know whether it will work or not or am i doing the wrong way?
This is most likely because you're trying to add the markers before the request to the database has finished resolving. This happens because the database/webservice request is most likely executed asynchronously.
Instead run the code for setting up the markers, when your promise from the database request have resolved. Like this:
var DirectoryController = function($scope, $rootScope, $http, $location, $route,DirectoryService, HomeService, $routeParams)
{
$scope.getAllCities = function()
{
DirectoryService.getAllCities().then(function(response){
$scope.cities = response.data;
console.log($scope.cities);
setupMapMarkers();
});
}
function setupMapMarkers(){
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(25,80),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
for (var i = 0; i < $scope.cities.length; i++){
createMarker($scope.cities[i]);
}
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
}
function createMarker(info){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
}
I am trying to render Google map with Latitude and Longitude from my MVC Model by using different examples. Google Map is displaying fine but it is not displaying the markers. I am very new to the Google Maps and feeling completely clueless about it. Can please anyone tell me how I can get the markers?
My MVC view is as follow
if (Model.WidgetType == "Map")
{
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$.get("/Home/GetMapLocations", function(data){
$.each(data, function(i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});
});
#*var data = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.lstMapLocations));
$.each(data, function (i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});*#
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>
}
MVC Controller is as follow
public ActionResult GetMapLocations()
{
var lstMapLocations = new List<MapLocation>();
var mapLocationModel1 = new MapLocation
{
EngineerName = "Engineer1",
SiteName = "Site1",
Latitude = 51.507351,
Longitude = -0.127758,
LstDouble = new List<double>()
};
var mapLocationModel2 = new MapLocation
{
EngineerName = "Engineer2",
SiteName = "Site2",
Latitude = 51.481728,
Longitude = -0.613576,
LstDouble = new List<double>()
};
var mapLocationModel3 = new MapLocation
{
EngineerName = "Engineer3",
SiteName = "Site3",
Latitude = 51.628611,
Longitude = -0.748229,
LstDouble = new List<double>()
};
var mapLocationModel4 = new MapLocation
{
EngineerName = "Engineer4",
SiteName = "Site4",
Latitude = 51.26654,
Longitude = -1.092396,
LstDouble = new List<double>()
};
lstMapLocations.Add(mapLocationModel1);
lstMapLocations.Add(mapLocationModel2);
lstMapLocations.Add(mapLocationModel3);
lstMapLocations.Add(mapLocationModel4);
foreach(var item in lstMapLocations)
{
item.LstDouble.Add(item.Latitude);
item.LstDouble.Add(item.Longitude);
item.LatLong = item.LstDouble.ToArray();
}
return Json(lstMapLocations);
}
I have found a work around to my problem and thought to share it for those who may stumble upon a similar issue. Courtesy stack overflow post particularly the answer posted by Atish Dipongkor. There may well be a better alternative to this problem but this approach has resolve my problem. I have made little change in that answer as Atish has used apostrophes while retrieving data from model which can break the functionality if any of the model field has string data with apostrophe in it. My appended solution with the above dummy data (in my question) is as follow
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 8,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
#foreach (var item in Model.lstMapLocations)
{
<text>
var markerLatLong = new google.maps.LatLng(#(item.Latitude), #(item.Longitude));
var markerTitle = #Html.Raw(Json.Encode(item.EngineerName));
var markerContentString = #Html.Raw(Json.Encode(item.EngineerName)) + " At " + #Html.Raw(Json.Encode(item.SiteName));
var infowindow = new google.maps.InfoWindow({
content: markerContentString
});
var marker = new google.maps.Marker({
position: markerLatLong,
title: markerTitle,
map: map,
content: markerContentString
});
google.maps.event.addListener(marker, 'click', (function (marker) {
return function () {
infowindow.setContent(marker.content);
infowindow.open(map, marker);
}
})(marker));
</text>
}
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>
Sorry for that newbie's question, but I didn't found any idea for that issue...
I would to create 4 markers (or more, but here it's 4) on a Google Map. I get the informations with a GET ajax request, responding with JSON. I'm able to create those markers, but I have a problem with the information window for each marker.
here the code I tried :
function readDevices(output){
// Get an array for the 4 devices with guid 42421 42422 42423 and 42424
var arrayOfDevices = new Array();
$.each(output.data, function(key, value){
$.each(value, function(deviceKey, deviceValue){
if(deviceKey == 'guid' && deviceValue >= 42421 && deviceValue <= 42424){
arrayOfDevices.push(value); // add the entire object in the tab
}
});
});
for(var i = 0; i < arrayOfDevices.length; i++){
var guid = arrayOfDevices[i]["guid"];
var latitude = arrayOfDevices[i]["latitude"];
var longitude = arrayOfDevices[i]["longitude"];
var name = arrayOfDevices[i]["name"];
var coord = new google.maps.LatLng(latitude, longitude);
var contentString = '<div id="content">'+
'<form method="get" action="manual" id="form-new">'+
'<button type="submit" id="new-button" name="'+guid+'" class="btn new-btn">Manual</button>'+
'</form>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: coord,
title: name
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}
This code put 4 markers, at the right place. But when I click on one of those markers, the "pop up window" appears near from the LAST marker that I have created. I would like to set information window for each marker.
I can't do something like :
var marker+i = new google.maps.Marker();
... But maybe there is tips for do some stuff like that ?
I hope it was clear ^^'
Thanks for helping, guys ! :-)
CORRECT CODE AFTER KhorneHoly answer ! Thanks to him.
function addMarker(markerData, map){
var contentString = '<div id="content">'+
'<form method="get" action="manual" id="form-new">'+
'<button type="submit" id="new-button" name="'+markerData["guid"]+'" class="btn new-btn">Manual</button>'+
'</form>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var LatLng = new google.maps.LatLng(markerData["latitude"], markerData["longitude"]);
var marker = new google.maps.Marker({
position: LatLng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
function readDevices(output){
var arrayOfDevices = new Array();
var markers = new Array();
$.each(output.data, function(key, value){
$.each(value, function(deviceKey, deviceValue){
if(deviceKey == 'guid' && deviceValue >= 42421 && deviceValue <= 42424){
arrayOfDevices.push(value);
}
});
});
for(var i = 0; i < arrayOfDevices.length; i++){
var guid = arrayOfDevices[i]["guid"];
var latitude = arrayOfDevices[i]["latitude"];
var longitude = arrayOfDevices[i]["longitude"];
var name = arrayOfDevices[i]["name"];
var coord = new google.maps.LatLng(latitude, longitude);
markers.push(addMarker(arrayOfDevices[i], map));
}
}
What you want to do is not possible because you can't generate variables like this. But what you can do is to generate an array you fill with the markers in an for loop like this:
var markers = new Array();
for (var i = 0; i < ArrayWithYourResultYouWantGenerateTheMarkersFrom.length; ++i) {
markers.push(addMarker(ArrayWithYourResultYouWantGenerateTheMarkersFrom.[i], map));
}
public function addMarker(markerData, map){
var LatLng = new google.maps.LatLng(markerData.lat, markerData.lon);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
}
I'm using the Google Places JavaScript API for a desktop application. However, the search results returned by the API aren't the same as the ones I get in maps.google.com. For instance, if I search for "Antique Hostel", I get many results (almost all of them are kinda random) whereas on Google Maps I get the correct (single) result.
Is the quality of the search isn't the same in the API and the service?
Here is my code
function initialize() {
// map setup
var mapOptions = {
center: new google.maps.LatLng(52.519171, 13.406091199999992),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
$map = document.getElementById('mapCanvas'),
map = new google.maps.Map($map, mapOptions),
input = document.getElementById('searchInput'),
autocomplete = new google.maps.places.Autocomplete(input),
service = new google.maps.places.PlacesService(map),
$ajaxSearchInput = $(input),
markers = [];
autocomplete.bindTo('bounds', map);
$ajaxSearchInput.keydown(function(e) {
if (e.keyCode === 13) {
var request = {
query: $(this).val(),
radius: '500',
location: map.getCenter()
}
service.textSearch(request, searchCallBack);
}
});
searchCallBack = function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
console.log(results);
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i], bounds);
}
map.fitBounds(bounds);
}
}
createMarker = function(place, bounds) {
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
// event listener to show the InfoWindow.
(function(marker, place) {
google.maps.event.addListener(marker, 'click', function() {
var content = '<h3>' + place.name + '</h3> ' + place.formatted_address + '<br>',
infowindow = new google.maps.InfoWindow({
content: ''
});
if (place.rating) {
content += '<p> <b>Rating</b>: ' + place.rating + '</p>';
}
if (place.types) {
content += '<p> <b>Tags</b>: ';
for (var j = 0, tag; tag = place.types[j]; j++) {
content += tag + ', '
}
content += '</p>';
}
infowindow.content = content;
infowindow.open(map, marker);
});
})(marker, place);
markers.push(marker);
bounds.extend(place.geometry.location);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
I have a FF error about the info window in GM. Here is the source code:
var lats;
var longs;
var k;
function initialize() {
//parentArray is an object where the elements of the parent page are stored
var parentArray = window.parent.params;
lats = parentArray["lat"].replace(/^\|+|\|+$/g, '').split("|");
longs = parentArray["long"].replace(/^\|+|\|+$/g, '').split("|");
k = parentArray["keys"].replace(/^\|+|\|+$/g, '').split("|");
var myLatlng = new google.maps.LatLng(parseFloat(lats[0]), parseFloat(longs[0]));
var myOptions = {
zoom: 20,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//contentString is built based on the array passed by the parent page
for (var i = 0; i < lats.length; i++) {
var contentString = '<div id="content"' + i + '><b>' + k[i] + '</b>';
for (var f in parentArray)
if ((f !== "long") && (f !== "lat") && (f !== "keys") && (parentArray[f].substring(0, 1) !== "<")) {
contentString += '<br />' + f + ': ' + parentArray[f];
}
contentString += '<br /></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(lats[i]), parseFloat(longs[i])),
map: map,
title: 'Position'
});
createInfoWindow(marker, contentString);
function createInfoWindow(m, content) {
google.maps.event.addListener(m, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, m);
});
}
}
}
params is an array with information and k is an array of keys for the markers on the google map. Does anybody know why do I have a FF error for this code?
Sample Data For params:
params['foo']: bar
params['keys']: "Start Position|End Position"
params['lat']: "12.5323703|13.5323703"
params['long']: "14.5786987|15.5786987"
EDIT:
The Error is: createInfoWindow is not defined
Thanks in advance,
Lajos Arpad.
You are defining your method inside a loop (this is bad on its own..) and you call the method before you define it ..
just moving the call below the definition fixes the issue..
function createInfoWindow(m, content) {
google.maps.event.addListener(m, 'click', function () {
infowindow.setContent(content);
infowindow.open(map, m);
});
}
createInfoWindow(marker, contentString);
Demo at http://jsfiddle.net/gaby/gdLVd/
But you should really move the definition of the createInfoWindow method somewhere else..
Better demo at http://jsfiddle.net/gaby/gdLVd/1/