Related
in my project i use google geometry location API to display marker on maps using site name not latitude and longitude. it is working fine. now, i want to display different marker for different site base on my database field resp. if resp is greater than 50 then marker is red and if less then 50 then marker is green. i tried it as below code. but it display all green or all red. if first value of resp is below 50 then all markers are green and if first value is greater than 50 then all markers are red. how can i display marker dynamically as value of resp? please help me. my code is
<script>
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(39.639537564366684, -97.03125),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map')[0], myOptions);
var addresses = [<?php $numItems = count($val); $i=0; foreach($val as $data){ echo "['".$data['name']."','".$data['resp']."']"; if(++$i !== $numItems) {echo ",";}}?>];
//var colordot =[];
//alert(addresses);
for (var x = 0; x < addresses.length; x++) {
//alert(addresses[x][1]);
if (addresses[x][1] >= 50) {
var img= 'img/red-dot.png';
}
else{
var img= 'img/green-dot.png';
}
//alert(colordot[x]);
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x][0]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
icon: img,
position: latlng,
map: map
});
});
}
});
</script>
One way to solve the problem would be with function closure on the img variable in the geocoder call:
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=' + addresses[x][0] + '&sensor=false', null, function(img) {
return function(data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
icon: img,
position: latlng,
map: map
});
}
}(img));
proof of concept fiddle
code snippet:
$(document).ready(function() {
var map;
var elevator;
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(39.639537564366684, -97.03125),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map')[0], myOptions);
var addresses = [
["New York, NY", 1],
["Boston, MA", 75]
];
for (var x = 0; x < addresses.length; x++) {
if (addresses[x][1] >= 50) {
var img = 'http://maps.google.com/mapfiles/ms/micons/red.png';
} else {
var img = 'http://maps.google.com/mapfiles/ms/micons/green.png';
}
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=' + addresses[x][0] + '&sensor=false', null, function(img) {
return function(data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
icon: img,
position: latlng,
map: map
});
}
}(img)).fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});;
}
});
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<div id="map"></div>
I had a similar issue with asynchronous geocoding and I eventually solved it with the method bind().
You could try:
var marker = new google.maps.Marker({
icon: img,
position: latlng,
map: map
});
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x][0]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
this.position = latlng;
this.icon = img;
}.bind(marker));
I am working on a google maps project where I am populating the google maps with markers being read from a database (drawMarkers function). Along with that the google maps finds your current location and keeps refreshing it every couple of seconds to keep track of you on the map. My issue is that have a var closest which is also a function i am using the too find the closest marker then create directions to current locations from there. I did not know how to actually find the closest marker so i borrowed the code from another question from stack overflow and tried to adapt it to this project. I need help to get my closest function to find the closest marker and then to make it the destination in the direction service
$ionicSideMenuDelegate.canDragContent(false);
$scope.getTourMarkers = function () {
tourmarkers.getTourMarkers().success(function (data) {
$scope.tourmarkers = data;
console.log($scope.tourmarkers);
drawMarkers();
});
};
var drawMarkers = function () {
var markers;
var content;
var infoWindow;
for (var i = 0; i < $scope.tourmarkers.length; i++) {
content = '<h2>' + $scope.tourmarkers[i].title + '</h2>' +
'<br />' +
'<p>' +
'</p>';
infoWindow = new google.maps.InfoWindow({
content: content
});
var point = new google.maps.LatLng($scope.tourmarkers[i].lat, $scope.tourmarkers[i].lon);
markers = new google.maps.Marker({
label: "S",
animation: google.maps.Animation.DROP,
position: point,
map: map,
info: content
});
//SCOPE: 'this' refers to the current 'markers' object, we pass in the info and marker
google.maps.event.addListener(markers, 'click', function () {
infoWindow.setContent(this.info);
infoWindow.open(map, this);
});
}
};
var myLatlng = new google.maps.LatLng(38.5602, -121.4241);
var NAPA_HALL_LAT_LNG = new google.maps.LatLng(38.553801, -121.4212745); // just created this marker for testing purposes
var mapOptions = {
center: myLatlng,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'SAC STATE'
});
var dest = new google.maps.Marker({
position: NAPA_HALL_LAT_LNG,
map: map,
title: 'NAPA HALL'
});
///////////////////Directions Display//////////////////////
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
//////////////////////////////////////////////////////////////////////////////////////////
//Goal of this function is to find closest marker to current location
//then to create directions to that marker.
//should be refreshed everytime in the onSuccess function
var closest = function (directionsService, directionsDisplay, marker, dest) {
var event;
function rad(x) {return x*Math.PI/180;}
function find_closest_marker( event ) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var R = 6371; // radius of earth in km
var distances = [];
var shortest = -1;
for( i=0;i < $scope.tourmarkers.length; i++) {
content = '<h2>' + $scope.tourmarkers[i].title + '</h2>' +
'<br />' +
'<p>' +
'</p>';
infoWindow = new google.maps.InfoWindow({
var mlat = $scope.tourmarkers[i].position.lat();
var mlng = $scope.tourmarkers[i].position.lng();
var dLat = rad(mlat - lat);
var dLong = rad(mlng - lng);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( shortest == -1 || d < distances[shortest] ) {
shortest = i;
}
}
alert(map.markers[shortest].title);
}
/////**directions feature should have the closest marker be the desitination//
directionsService.route({
origin: marker.position,
destination: dest.position, // i think the marker that should in here is shortest.
travelMode: google.maps.TravelMode.WALKING
}, function(response,status) {
if(status==google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
//////////////////////////////////////////////////////////////////////////////////////////
var onSuccess = function (position) {
marker.setPosition(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
directionsDisplay.setMap(map);
dest.setPosition(new google.maps.LatLng(38.553801, -121.4212745));
//dest.setPosition((closest(marker, $scope.tourmarkers)).position); // if you can get this line to work without commenting it out then you're set
closest(directionsService,directionsDisplay, marker,dest);
$scope.map = map;
//$scope.map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.watchPosition(onSuccess, onError, {
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true
});
Everything in this project is working properly except that closest function. but even then i have already tested the directionservice and even that is working too. I just need help making the destination in the direction service to be the closest marker to current location.
i think this code is helpful for you i used this code in my project such that your requirement same as my requirement
in the below function 'data' means list of lat lng's from server
function initialize(data) {
size = 0;
counts = 0;
stops = data;
size = stops.length;
if (stops.length > 0) {
var map = new window.google.maps.Map(document
.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer(
{
suppressMarkers : true,
polylineOptions : {
strokeColor : "black"
}
});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map,stops);
/* if (stops.length > 1) */
window.tour.calcRoute(stops,directionsService,
directionsDisplay,size);
}
}
function Tour_startUp(stops) {
var stops=stops;
var counts=0;
if (!window.tour) window.tour = {
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom:10,
center: new window.google.maps.LatLng(17.379818, 78.478542), // default to Hyderabad
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map,stops) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (stops,directionsService, directionsDisplay,size) {
size=size;
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
var tempp=0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
tempp++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].latitude, stops[j].longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
//delay(600);
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
//alert("count test");
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
var totdist=0;
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
var markerletter2= "B".charCodeAt(0)
markerletter += i;
markerletter2 += i;
markerletter = String.fromCharCode(markerletter);
markerletter2 = String.fromCharCode(markerletter2);
createMarker(directionsDisplay.getMap(),legs[i].start_location,legs[i].start_address,markerletter,size);//To display location address on the marker
var routeSegment = i + 1;
var point=+routeSegment+1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += '<b>Point '+ routeSegment +' :</b>'+ ' ' +legs[i].start_address + ' <br> ';
summaryPanel.innerHTML += '<b>Point '+ point +' :</b>'+ ' '+legs[i].end_address + '<br>';
summaryPanel.innerHTML += '<b>Distance Covered '+' :</b>'+legs[i].distance.text + '<br><br>';
var test=legs[i].distance.text.split(' ');
var one=parseFloat(test[0]);
if(test[1]=="m"){
var one=parseFloat(test[0]/1000);
}
totdist=parseFloat(totdist)+parseFloat(one);
}
summaryPanel.innerHTML += '<b> Total Distance :'+totdist + 'km'+ '</b><br><br>';
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,legs[legs.length-1].end_address,markerletter,size);
}
}
});
})(k);
function delay(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
}
}//calculate route end
};
}
//to show information on clicking marker
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
function getMarkerImage(iconStr,size) {
counts++;
if(counts==size){
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/blue.png";
counts = 0;
}else{
if (iconStr=="undefined") {
iconStr = "red";
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
else{
var markerimageLoc="http://www.google.com/mapfiles/marker"+ iconStr +".png";
// var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
}
icons[iconStr] = new google.maps.MarkerImage(markerimageLoc,
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(25, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
return icons[iconStr];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function createMarker(map, latlng, label, character,size) {
var markerletter = character;
var size=size;
if (/[^a-zA-Z]/.test(character)) {
var markerletter = "undefined";
}
var contentString = '<b>' + label + '</b><br>';
var marker = new google.maps.Marker({
position : latlng,
map : map,
shadow : iconShadow,
icon : getMarkerImage(markerletter,size),
shape : iconShape,
title : label,
zIndex : Math.round(latlng.lat() * -100000) << 5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
return marker;
}
I want to move 2 markers on the same google map but i can't find the problem in my code. I can move the 1st marker but i can't move the second one, it is possible to move two markers at the same time on the same map?
How i can move 2 markers at the same time?
<!DOCTYPE html>
<html>
<head>
<title>HTML5</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=650, user-scalable=yes">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<style>
html, body {
height: 100%;
margin: 0;
}
#mapcanvas {
height: 97%;
}
#info {
width: auto;
margin: 5px;
height: 3%;
}
</style>
<script>
var map;
var latLonList = [
{ lat: 45.54169245190391, lon: -73.53928729891777 },
{ lat: 45.54173002374242, lon: -73.53945091366768 },
{ lat: 45.541743173879944, lon: -73.53949382901192 },
{ lat: 45.541790138631775, lon: -73.53962525725365 },
{ lat: 45.541844617694764, lon: -73.53980496525764 },
{ lat: 45.54189721811927, lon: -73.5399578511715 },
{ lat: 45.54193666840536, lon: -73.5401026904583 },
{ lat: 45.54198363299557, lon: -73.5402475297451 },
{ lat: 45.542068169159045, lon: -73.5405720770359 },
{ lat: 45.54214706946365, lon: -73.54082688689232 },
{ lat: 45.54222221250792, lon: -73.54105487465858 },
{ lat: 45.54226729828628, lon: -73.54119434952736 },
{ lat: 45.54235746973452, lon: -73.54123994708061 },
{ lat: 45.542543447889805, lon: -73.5411112010479 },
{ lat: 45.542718154081314, lon: -73.54099586606026 },
{ lat: 45.54289661683465, lon: -73.54089394211769 },
{ lat: 45.54298866582284, lon: -73.54103341698647 },
{ lat: 45.54308071466031, lon: -73.54133650660515 },
{ lat: 45.543180277518914, lon: -73.5413445532322 },
{ lat: 45.54330050413203, lon: -73.54127749800682 },
{ lat: 45.54337001002545, lon: -73.54111924767494 }
]
$(document).ready(function () {
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(43, 0),
};
map = new google.maps.Map($('#mapcanvas')[0], mapOptions);
//*********************************************************************
// Add the layer showing the inventory
//*********************************************************************
var marker = null;
var markerTwo = null;
var i = 0;
var j = 1;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function (position) {
var newPoint = new google.maps.LatLng(latLonList[i].lat, latLonList[i].lon);
var secondPoint = new google.maps.LatLng(latLonList[j].lat, latLonList[j].lon);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map,
draggable: true
});
}
if (markerTwo) {
// Marker already created - Move it
markerTwo.setPosition(secondPoint);
}
else {
// Marker does not exist - Create it
markerTwo = new google.maps.Marker({
position: secondPoint,
map: map,
draggable: true
});
}
map.setCenter(newPoint);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 3000);
if (i == 20) {
i = 0
}
else {
i++;
}
}
if (j == 19) {
j = 0
}
else {
j++;
}
autoUpdate();
});//end document ready
</script>
</head>
<body>
<div id="info">trying to update location every 5 secs - new latitude longitude : <span id="coordinates"></span></div>
<div id="mapcanvas">
</div>
</body>
</html>
the answer:
map=new google.maps.Map($('#mapcanvas')[0], mapOptions);
//*********************************************************************
// Add the layer showing the inventory
//*********************************************************************
var marker = null;
var marker2 = null ;
var i = 0;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function(position, pos) {
//var newPoint = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var newPoint = new google.maps.LatLng(latLonList[i].lat, latLonList[i].lon);
var myLatlng = new google.maps.LatLng(latLonList[i+1].lat, latLonList[i+1].lon);
if (marker2) {
// Marker already created - Move it
marker2.setPosition(myLatlng);
}
else {
marker2 = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Client 2'
});
}
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map,
title: 'Client 1'
});
}
// Center the map on the new position
map.setCenter(myLatlng);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 3000);
if (i == 19)
i = 0
else
i++;
}
autoUpdate();
});//end document ready
http://geekonjava.blogspot.in/2014/10/how-to-make-animated-moving-marker-on.html
Follow This link It Will Helps You
html{height:100%;}
body{height:100%;margin:0px;font-family: Helvetica,Arial;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>GeekOnJava: Directions Complex</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script>
<script type="text/javascript">
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var position;
var marker = [];
var polyline = [];
var poly2 = [];
var poly = null;
var startLocation = [];
var endLocation = [];
var timerHandle = [];
var speed = 0.000005, wait = 1;
var infowindow = null;
var myPano;
var panoClient;
var nextPanoId;
var startLoc = new Array();
startLoc[0] = 'rio claro, trinidad';
startLoc[1] = 'preysal, trinidad';
startLoc[2] = 'san fernando, trinidad';
startLoc[3] = 'couva, trinidad';
var endLoc = new Array();
endLoc[0] = 'princes town, trinidad';
endLoc[1] = 'tabaquite, trinidad';
endLoc[2] = 'mayaro, trinidad';
endLoc[3] = 'arima, trinidad';
var Colors = ["#FF0000", "#00FF00", "#0000FF"];
function initialize() {
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var myOptions = {
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
address = 'Trinidad and Tobago'
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
map.fitBounds(results[0].geometry.viewport);
});
// setRoutes();
}
function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
function setRoutes(){
var directionsDisplay = new Array();
for (var i=0; i< startLoc.length; i++){
var rendererOptions = {
map: map,
suppressMarkers : true,
preserveViewport: true
}
directionsService = new google.maps.DirectionsService();
var travelMode = google.maps.DirectionsTravelMode.DRIVING;
var request = {
origin: startLoc[i],
destination: endLoc[i],
travelMode: travelMode
};
directionsService.route(request,makeRouteCallback(i,directionsDisplay[i]));
}
function makeRouteCallback(routeNum,disp){
if (polyline[routeNum] && (polyline[routeNum].getMap() != null)) {
startAnimation(routeNum);
return;
}
return function(response, status){
if (status == google.maps.DirectionsStatus.OK){
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation[routeNum] = new Object();
endLocation[routeNum] = new Object();
polyline[routeNum] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
poly2[routeNum] = new google.maps.Polyline({
path: [],
strokeColor: '#FFFF00',
strokeWeight: 3
});
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
disp = new google.maps.DirectionsRenderer(rendererOptions);
disp.setMap(map);
disp.setDirections(response);
//Markers
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation[routeNum].latlng = legs[i].start_location;
startLocation[routeNum].address = legs[i].start_address;
// marker = google.maps.Marker({map:map,position: startLocation.latlng});
marker[routeNum] = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation[routeNum].latlng = legs[i].end_location;
endLocation[routeNum].address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline[routeNum].getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
}
}
}
}
polyline[routeNum].setMap(map);
//map.fitBounds(bounds);
startAnimation(routeNum);
} // else alert("Directions request failed: "+status);
}
}
var lastVertex = 1;
var stepnum=0;
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol= [];
//----------------------------------------------------------------------
function updatePoly(i,d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2[i].getPath().getLength() > 20) {
poly2[i]=new google.maps.Polyline([polyline[i].getPath().getAt(lastVertex-1)]);
// map.addOverlay(poly2)
}
if (polyline[i].GetIndexAtDistance(d) < lastVertex+2) {
if (poly2[i].getPath().getLength()>1) {
poly2[i].getPath().removeAt(poly2[i].getPath().getLength()-1)
}
poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),polyline[i].GetPointAtDistance(d));
} else {
poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),endLocation[i].latlng);
}
}
//----------------------------------------------------------------------------
function animate(index,d) {
if (d>eol[index]) {
marker[index].setPosition(endLocation[index].latlng);
return;
}
var p = polyline[index].GetPointAtDistance(d);
//map.panTo(p);
marker[index].setPosition(p);
updatePoly(index,d);
timerHandle[index] = setTimeout("animate("+index+","+(d+step)+")", tick);
}
//-------------------------------------------------------------------------
function startAnimation(index) {
if (timerHandle[index]) clearTimeout(timerHandle[index]);
eol[index]=polyline[index].Distance();
map.setCenter(polyline[index].getPath().getAt(0));
poly2[index] = new google.maps.Polyline({path: [polyline[index].getPath().getAt(0)], strokeColor:"#FFFF00", strokeWeight:3});
timerHandle[index] = setTimeout("animate("+index+",50)",2000); // Allow time for the initial map display
}
//----------------------------------------------------------------------------
</script>
</head>
<body onload="initialize()">
<div id="tools">
<button onclick="setRoutes();">Start</button>
</div>
<div id="map_canvas" style="width:100%;height:100%;"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>GeekOnJava: Directions Complex</title>
<style>
html
{
height:100%;
}
body
{
height:100%;
margin:0px;
font-family: Helvetica,Arial;
}
</style>
<script type="text/javascript">
var map;
var geocoder;
var marker;
var people = new Array();
var people2 = new Array();
var latlng;
var infowindow;
var lats=6.9271;
var markersz = new google.maps.Marker;
var markers2 = new google.maps.Marker;
$(document).ready(function() {
var mapOptions = {
center: new google.maps.LatLng(7.8731, 80.7718), // Coimbatore = (11.0168445, 76.9558321)
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
ViewCustInGoogleMap();
});
window.setInterval(function(){
ViewCustInGoogleMap();
}, 5000);
function ViewCustInGoogleMap() {
//deleting the previous set mark on the map
markersz.setMap(null);
markers2.setMap(null);
lats = lats+0.01;
// Get data from database. It should be like below format or you can alter it.
var data = '[{ "DisplayText": "DULA TEST<br/><h1>HHH</h1><a href=https://www.google.lk?st=kk target=_blank>CLICK</a>", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "'+lats+',79.8612", "MarkerId": "Customer"}]';
people = JSON.parse(data);
for (var i = 0; i < people.length; i++) {
markersz = setMarker(people[i]);
}
//-----------------------------------------------------------------------------------------------------------------
//getting lats and longs from the controller
$.ajax({
type: 'post',
url: 'http://localhost/GPS/Login/latsAndLongs',
data: "",
dataType: 'json',
success: function(response) {
people2 = JSON.parse(response);
for (var i = 0; i < people2.length; i++) {
//setting the current mark and returning the mark object so that it can be deleted in the next iteration
markers2=setMarker2(people2[i]);
}
}
});
//var data2 = '[{ "DisplayText": "DULA TEST2", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "6.5854,79.9607", "MarkerId": "Seller"}]';
}
//---------------------------------------------------------------------
function setMarker(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
//alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
marker = new google.maps.Marker;
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"], // Content display on marker click
icon: "http://www.myiconfinder.com/uploads/iconsets/256-256-a5485b563efc4511e0cd8bd04ad0fe9e.png" // Give ur own image
});
//marker.setMap(null);
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
return marker;
}
}
//-----------------------------
function setMarker2(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"], // Content display on marker click
icon: "https://cdn4.iconfinder.com/data/icons/iconsimple-places/512/pin_1-128.png" // Give ur own image
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
return marker;
}
</script>
Move a list of marker and zoom particular marker while iterating.
1. Get Imei_no.
2. Push imei_no in variable.
3. Create Map.
4. Get details based on imei_no.
5. Create Maker.
6. Push maker in test.
7. Delete marker.
8. Return to autoUpdate.
Live Tracking Done by Sureshchan...
if (true) {
var listimei = [];
$scope.listimei = [];
$http.get('school/transport/scroute/viewIMEI?imeiNo=' + routeid).success(function(response) {
//1.
console.log(response);
if (response.viewRoute == 0) {
logger.logError("IMEI No. not available");
$state.go("app.school.scTransport.scVehicleTracking.list");
} else {
//brown
$scope.brown = response.viewRoute[0].emptveh;
//2.
for (var b = 0; b < response.viewRoute.length; b++) {
listimei.push(response.viewRoute[b].imeiNo);
}
//3.
var mapOptions = {
center: new google.maps.LatLng(13.0037, 80.1476),
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('viewallmap'), mapOptions);
var infoWindow = new google.maps.InfoWindow;
var test = [];
var marker;
function autoUpdate() {
if (marker == null){
$scope.locData = [];
var y = 0;
var g = 0;
var r = 0;
var n = 0;
$http.get('school/transport/scroute/getListImei?imeiNo=' + listimei).success(function(response) {
//4.
console.log(response);
$scope.assetloader = true;
for(var l = 0;l<response.viewImeiList.length;l++){
//time
var startTime = new Date();
var endTime = new Date(response.viewImeiList[l].lastmove);
var difference = startTime.getTime() - endTime.getTime();
var resultInMinutes = difference / 60000;
var result = Math.round(resultInMinutes);
//for date
var dateObj = new Date(response.viewImeiList[l].lastmove);
var month1 = ("0" + (dateObj.getUTCMonth() + 1)).slice(-2);//months from 1-12
var day1 = ("0" + dateObj.getUTCDate()).slice(-2);
var year1 = dateObj.getUTCFullYear();
var testdate = year1 + "-" + month1 + "-" + day1;
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
if (response.viewImeiList[l].nosignal == 1) {
$scope.black = n + 1;
n++;
}else if(testdate != today){
$scope.black = n + 1;
n++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title,response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "000000","FFFFFF");
$scope.locData.push($scope.view);
}
else if (response.viewImeiList[l].speed == 0) {
$scope.yellow = y + 1;
y++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title,response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "e5ff00","000000");
$scope.locData.push($scope.view);
} else if (response.viewImeiList[l].speed != 0 && result > 15) {
$scope.yellow = y + 1;
y++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "e5ff00","000000");
$scope.locData.push($scope.view);
} else if (response.viewImeiList[l].speed > 50 && result < 15) {
$scope.red = r + 1;
r++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "FF0000","000000");
$scope.locData.push($scope.view);
} else {
$scope.green = g + 1;
g++;
var title = '<b>Vehicle No : </b> ' + response.viewImeiList[l].vehname + '<br> <b>IMEI No : </b> ' + response.viewImeiList[l].imeiNo + '<br> <b>Reg No : </b> ' + response.viewImeiList[l].regno + '<br> <b> Speed : </b> ' + response.viewImeiList[l].speed + ' KMPH <br> <b> Over Speed Limit : </b> 50 KMPH <br> <b> Last Movement Detected Time : </b> ' + response.viewImeiList[l].lastmove + '<br>';
$scope.view = [];
$scope.view.push(response.viewImeiList[l].vehname, title, response.viewImeiList[l].latitude, response.viewImeiList[l].longitude, "00ff00","000000");
$scope.locData.push($scope.view);
}
}
var locations = $scope.locData;
for (var i = 0; i < locations.length; i++) {
var city = locations[i][0];
var state = locations[i][1];
var lat = locations[i][2];
var lng = locations[i][3];
var desc = locations[i][4];
var textcol = locations[i][5];
var z = i;
var myLatLng = new google.maps.LatLng(lat, lng);
var content = '<div class="map-content"><h3>' + state +
'</h3></div>';
//5.
marker = new google.maps.Marker({
map: map,
title: state,
position: myLatLng,
icon : 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + city + '|' + desc + '|' +textcol,
draggable : true,
zIndex: z
});
//6.
test.push(marker);
//mouseover
google.maps.event.addListener(marker, 'click', (function(marker, content) {
return function() {
infoWindow.setContent(content);
infoWindow.open(map, marker);
}
})(marker, content));
// add the double-click event listener
google.maps.event.addListener(marker, 'dblclick', function(event){
map = marker.getMap();
map.setCenter(overlay.getPosition()); // set map center to marker position
smoothZoom(map, 12, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
})
// the smooth zoom function
function smoothZoom (map, max, cnt) {
if (cnt >= max) {
return;
}
else {
y = google.maps.event.addListener(map, 'zoom_changed', function(event){
google.maps.event.removeListener(y);
self.smoothZoom(map, max, cnt + 1);
});
setTimeout(function(){map.setZoom(cnt)}, 80);
}
}
}
});
myVar = setTimeout(autoUpdate, 40000);
}
if(test.length !=0){
//7.
for (var k = 0; k < test.length; k++) {
if (test[k].getMap() != null) {
test[k].setMap(null);
}
}
test1();
}
}
function test1(){
//8.
test = [];
marker = null;
autoUpdate();
}
autoUpdate();
}
});
}
Google map is not showing the exact location. I'm taking the address from our clients and will display them the map. I cross checked the google lat and long with mine, it is not returning the exact values. Here is my code, if I am wrong, please guide me.
function callMap() {
var fullAddress = address + "," + city + "," + state + "," + zip;
var lat_Company = "";
var lng_Company = "";
geocoder.geocode({
'address': fullAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat_Company = parseFloat(results[0].geometry.location.lat());
lng_Company = parseFloat(results[0].geometry.location.lng());
var lCompanyObject = new Object();
lCompanyObject.Name = companyDetails.CompanyName;
lCompanyObject.Description = address + "<br/>" + city + ", " + state + "," + zip;
lCompanyObject.FullAddress = address + ", " + city + ", " + state + "," + zip;
lCompanyObject.Lat = lat_Company;
lCompanyObject.Lng = lng_Company;
displayCompany(city, state, "comp_map", "mapinfowindow", lCompanyObject, "fromSideBar");
}
});
var abpoutsideBarBuilder = '<ul>' +
'<li><div id="map_wrapper1">' +
'<div id="comp_map1"></div>' +
'<div id="mapinfowindow"style="display:none" ><b>#name</b><br>#description</div></div></li></ul>';
$('.about_map_addr_businesshours').html(abpoutsideBarBuilder);
}
function displayCompany(pCity, pState, pMapDiv, mapinfowindow, lCompany, from) {
var requestLocation = lCompany.FullAddress;
geocoder.geocode({
'address': requestLocation
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = parseFloat(results[0].geometry.location.lat());
var lng = parseFloat(results[0].geometry.location.lng());
if (lat != null && lng != null) {
centerLat = lat;
centerLng = lng;
initDisplayMap(centerLat, centerLng, pMapDiv, mapinfowindow, lCompany, from);
}
} else {
console.error("Geocode was not successful for the following reason ::" + status);
}
});
}
function initDisplayMap(pCenterLat, pCenterLng, pMapDiv, mapinfowindow, pCompany, from) {
if ($("#" + mapinfowindow).length > 0) {
var latlng = new google.maps.LatLng(pCenterLat, pCenterLng);
var myOptions = {
zoom: 14,
center: latlng,
disableDefaultUI: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(pMapDiv), myOptions);
var infowindow = null;
infowindow = new google.maps.InfoWindow({});
var LatLngList = new Array();
var marker = pCompany;
var markerHTML = $('#mapinfowindow').clone().html();
if (from.indexOf("fromSideBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
} else if (from.indexOf("fromAboutBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
}
if (marker.Lat != null && marker.Lng != null) {
var myLatLng = new google.maps.LatLng(marker.Lat, marker.Lng);
LatLngList[LatLngList.length] = myLatLng;
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
clickable: true,
html: markerHTML
});
google.maps.event.addListener(beachMarker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
var bounds = new google.maps.LatLngBounds();
if (LatLngList.length > 1) {
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend(LatLngList[i]);
}
//Fit these bounds to the map
map.fitBounds(bounds);
map.setZoom(map.getBoundsZoomLevel(bounds));
map.setCenter(beachMarker.getPosition());
}
}
}
}
Don't mix up geocoder an places.
Nakedcherry Waxing Boutique 6th Street Parkhurst,South Africa
the bold part of this string obviously isn't a address-component.
Expecting the desired result is as when I would expect to get my location for a query like
Dr.Molle,Berlin,Germany
The result you get by the geocoder is for 6th Street Parkhurst,South Africa, and the result is correct.
When you look for a place use the places-textsearch, the result for the given query will be: -26.1437060,28.0207660
Trying to simplify my google maps custom code to put markers and an info bubble. However have run into a few issues which I can't seem to debug the code is below, it's currently outputting nothing. The code defines lat/long/title and content and then trys to ouput them as markers on a map.
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(20,0);
var myOptions = {
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var countries = [
{title:'Afghanistan', lat:34.28, lon:69.11, content:"<h2>Afghanistan</h2><p>16 Alumni</p>"},
{title:'Albania', lat:41.18, lon:19.49, content:"<h2>Albania</h2><p>7 Alumni</p>"},
{title:'Angola', lat:-8.5, lon:13.15, content:"<h2>Angola</h2><p>9 Alumni</p>"},
{title:'Antarctica', lat:-80, lon:0, content:"<h2>Antarctica</h2><p>1 Alumnus</p>"},
{title:'Antigua & Barbuda', lat:17.20, lon:-61.48, content:"<h2>Antigua & Barbuda</h2><p>1 Alumnus</p>"},
{title:'Argentina', lat:-36.30, lon:-60, content:"<h2>Argentina</h2><p>29 Alumni</p>"},
];
for (i=0;i<countries.length;i++)
{
c = countries[i];
marker: new google.maps.Marker({position: new google.maps.LatLng(" + c['lat'] + "," + c['lon'] + "), map: map, title: '" + c['title'] + "'}),
infowindow: new google.maps.InfoWindow({content: '" + c['content'] + "'});
}
var item;
for (var i=0; i<countries.length; i++) {
item = countries[i];
google.maps.event.addListener(item.marker, 'click', makeCallback(item));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
}
</script>
There are various typographical and syntax errors in the code. Also there is no need to construct strings in the place of variables. The following is a working version:
...
var countries = [...];
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
c.marker = new google.maps.Marker({
position: new google.maps.LatLng(c.lat, c.lon),
map: map,
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}