I'de like to have all Markers set when initializing
the page and when the mouse is out of the div. When the mouse is on one of the div, the Marker related to this div remains and the other ones are removed until mouseleave.
So I tried to remove all markers with setMapOnAll(null) and add the one specific to the div on mouseover, and then reset all markers on mouseleave.
But I cant make the Markers disappear.
Javascript:
<script>
var infoWindow = new google.maps.InfoWindow();
function initialize() {
var map = new google.maps.Map(
document.getElementById("map"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var name = "name1";
var address = "address 1";
var condition = "true";
var point = new google.maps.LatLng(42, -72);
var html = "<b>" + name + "</b> <br/>" + address;
var i = 0;
createMarker(point, condition,html, i, map);
point = new google.maps.LatLng(42.02, -72.02);
name = "name2";
address = "address 2";
html = "<b>" + name + "</b> <br/>" + address;
condition = "false";
i++;
var marker = createMarker(point, condition, html, i, map);
map.setCenter(marker.getPosition());
}
function createMarker(point, condition, html, i, map) {
var marker = new google.maps.Marker({
map: map,
position: point,
draggable: true
});
var activeIcon, idleIcon;
if (condition == "true") {
idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
} else {
idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
}
marker.setIcon(idleIcon);
var elem = document.getElementById('a' + i);
if (!!elem) {
elem.onmouseover = function() {
setMapOnAll(marker, null);
marker.setIcon(idleIcon);
}
elem.onmouseleave = function() {
setMapOnAll(marker, map);
}
}
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
return marker;
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
function setMapOnAll(marker, map) {
for (var i = 0; i < marker.length; i++) {
marker[i].setMap(map);
}
}
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
html:
<div id="a0">marker 1</div>
<div id="a1">marker 2</div>
<div id="map"></div>
CSS:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
Just change the example in that question to set the map property of the marker on mouseover of the external div, and set it back to null on mouseleave.
code snippet:
function createMarker(point, icon, html, i, map) {
var marker = new google.maps.Marker({
position: point,
draggable: true
});
marker.setIcon(icon);
var elem = document.getElementById('a' + i);
if (!!elem) {
elem.onmouseover = function() {
marker.setMap(map);
}
elem.onmouseleave = function() {
marker.setMap(null);
}
document.getElementById('a' + i).onclick = (function(marker) {
return function() {
google.maps.event.trigger(marker, 'click');
}
})(marker);
}
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
return marker;
}
var infoWindow = new google.maps.InfoWindow();
var markers = [];
var map;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var name = "name1";
var address = "address 1";
var point = new google.maps.LatLng(42, -72);
var html = "<b>" + name + "</b> <br/>" + address;
var i = 0;
createMarker(point, 'http://labs.google.com/ridefinder/images/mm_20_blue.png', html, i, map);
point = new google.maps.LatLng(42.02, -72.02);
name = "name2";
address = "address 2";
html = "<b>" + name + "</b> <br/>" + address;
i++;
var marker = createMarker(point, 'http://labs.google.com/ridefinder/images/mm_20_green.png', html, i, map);
point = new google.maps.LatLng(42.01, -72.01);
name = "name3";
address = "address 3";
html = "<b>" + name + "</b> <br/>" + address;
i++;
var marker = createMarker(point, 'http://labs.google.com/ridefinder/images/mm_20_red.png', html, i, map);
map.setCenter(marker.getPosition());
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="a0">marker 1</div>
<div id="a1">marker 2</div>
<div id="a2">marker 3</div>
<div id="map_canvas"></div>
Related
I have multiple markers on the map that I have imported from JSON. Inside the marker infowindow I have a button and when clicking on that, I want to change the marker image. Please check my code below. Marker list and Infowindow is working fine. I just want to do some actions on the button that is inside infowindow.
var workerlist;
var jobprice;
var price;
var map;
var list;
var position;
var image;
var image1;
var marker;
function myMap() {
var mapProp= {
center:new google.maps.LatLng(30.7333,76.7794),
zoom:10,
disableDefaultUI: true
};
map = new google.maps.Map(document.getElementById("map"),mapProp);
image = 'images/blue_marker1.png';
image1 = 'images/pink_marker1.png';
console.log(workerlist);
for (var i = 0; i < workerlist.length; i++) {
list = workerlist[i];
price = jobprice;
position = new google.maps.LatLng(list.latitude,list.longitude);
addMarker(map,list,price,position,marker);
}
}
function addMarker(map,list,price,position,marker){
marker = new google.maps.Marker({
position: position,
title: list.name,
map: map,
icon: image
});
var contentString = '<div class="mapBox">'+
'<div class="content"> <h3>'+ list.name +
'</h3>'+
'<h6>(2.1 miles from the job venue)</h6>' +
'<div class="rating"></div>'+
'<p>Total cost to hire:</p>'+
'<p>Rate: $' + price.Price + ' per hour</p>'+
'<p>Total Cost: $'+ price.total_amount +'</p>'+
'</div><button id="shortList" class="btn btn-shortlist" onclick="shortList()">Shortlist for the JOb</button>'+
'</div>';
marker.addListener('click', function() {
if (typeof infowindow != 'undefined') infowindow.close();
infowindow = new google.maps.InfoWindow({
content: contentString,
})
infowindow.open(map,marker)
$("#shortList").click(function(){
image = 'images/pink_marker1.png';
});
});
}
function shortList(){
// alert('clicked');
// infowindow.close();
//marker.setIcon(image1);
}
Before you can access the <button id="shortList"> in the DOM with JQuery, it needs to be added to the DOM. That happens asynchronously when the InfoWindow content is rendered, the domready event on the InfoWindow fires when it is available.
google.maps.event.addListener(infowindow, 'domready', function() {
$("#shortList").click(function() {
// code here to change the icon
});
});
related question: How to detect button click in googlemaps infowindow
If you want the icon of the marker to change, you need to call .setIcon on the marker:
marker.addListener('click', function() {
if (typeof infowindow != 'undefined') infowindow.close();
infowindow = new google.maps.InfoWindow({
content: contentString,
})
infowindow.open(map, marker)
var that = this; // save reference to marker to change its icon
google.maps.event.addListener(infowindow, 'domready', function() {
$("#shortList").click(function() {
image = 'http://maps.google.com/mapfiles/ms/micons/orange.png';
that.setIcon(image);
});
});
});
proof of concept fiddle
code snippet:
var workerlist;
var jobprice = {
Price: "$10",
total_amount: "$100"
};
var price;
var map;
var list;
var position;
var image;
var image1;
var marker;
workerlist = [{
name: "Chandigarth",
latitude: 30.7333,
longitude: 76.7794
},
{
name: "Chandigarth2",
latitude: 30.7,
longitude: 76.7
}
]
function myMap() {
var mapProp = {
center: new google.maps.LatLng(30.7333, 76.7794),
zoom: 10,
disableDefaultUI: true
};
map = new google.maps.Map(document.getElementById("map"), mapProp);
image = 'http://maps.google.com/mapfiles/ms/micons/blue.png';
image1 = 'http://maps.google.com/mapfiles/ms/micons/orange.png';
console.log(workerlist);
for (var i = 0; i < workerlist.length; i++) {
list = workerlist[i];
price = jobprice;
position = new google.maps.LatLng(list.latitude, list.longitude);
addMarker(map, list, price, position, marker);
}
}
function addMarker(map, list, price, position, marker) {
marker = new google.maps.Marker({
position: position,
title: list.name,
map: map,
icon: image
});
var contentString = '<div class="mapBox">' +
'<div class="content"> <h3>' + list.name +
'</h3>' +
'<h6>(2.1 miles from the job venue)</h6>' +
'<div class="rating"></div>' +
'<p>Total cost to hire:</p>' +
'<p>Rate: $' + price.Price + ' per hour</p>' +
'<p>Total Cost: $' + price.total_amount + '</p>' +
'</div><button id="shortList" class="btn btn-shortlist" onclick="shortList()">Shortlist for the JOb</button>' +
'</div>';
marker.addListener('click', function() {
if (typeof infowindow != 'undefined') infowindow.close();
infowindow = new google.maps.InfoWindow({
content: contentString,
})
infowindow.open(map, marker)
var that = this;
google.maps.event.addListener(infowindow, 'domready', function() {
$("#shortList").click(function() {
image = 'http://maps.google.com/mapfiles/ms/micons/orange.png';
that.setIcon(image);
});
});
});
}
function shortList() {
// alert('clicked');
// infowindow.close();
//marker.setIcon(image1);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Info Windows</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=myMap&libraries=&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>
If i want to move the marker and i click "YES" in confirmation alert the marker will move to dragend position but i have problem when i click "NO" in confirmation alert. the marker should move to dragstart position but in current code the marker stay in dragend position not in dragstart position. anyone please help me. thankyou
<!DOCTYPE html>
<html>
<body>
<p><span id="start"></span></p>
<p><span id="end"></span></p>
<div id="map" style="width:100%;height:500px"></div>
<script>
function initMap() {
var theLat = 51.508742;
var theLng = -0.120850;
var displayMap = document.getElementById("map");
var myLatlng = new google.maps.LatLng(theLat, theLng);
var myOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(displayMap, myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function() {
if (confirm("Are You Sure You Want To Move this marker?")) {
var positionStartLatNew = this.position.lat();
var positionStartLngNew = this.position.lng();
document.getElementById('end').innerHTML = "Lat end : " + positionStartLatNew + ", " + "Lng end : " + positionStartLngNew;
} else {
google.maps.event.addListener(marker, 'dragstart', function() {
var positionStartLat = this.position.lat();
var positionStartLng = this.position.lng();
document.getElementById('start').innerHTML = "Lat start : " + positionStartLat + ", " + "Lng start : " + positionStartLng;
});
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDuDtGMwgHfy9Nb07ARmHlsT-Zen228uK4&callback=initMap"></script>
</body>
</html>
Save the position in an accessible scope on dragstart. Use that position to revert the marker when the confirm dialog is cancelled:
var positionStart, positionStartNew;
google.maps.event.addListener(marker, 'dragstart', function() {
positionStart = this.position;
document.getElementById('start').innerHTML = "start position: " + positionStart.toUrlValue(6);
});
google.maps.event.addListener(marker, 'dragend', function() {
if (confirm("Are You Sure You Want To Move this marker?")) {
positionStartNew = this.position;
document.getElementById('end').innerHTML = "end position: " + positionStartNew.toUrlValue(6);
} else {
marker.setPosition(positionStart);
}
});
proof of concept fiddle
code snippet:
function initMap() {
var theLat = 51.508742;
var theLng = -0.120850;
var displayMap = document.getElementById("map");
var myLatlng = new google.maps.LatLng(theLat, theLng);
var myOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(displayMap, myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true
});
var positionStart, positionStartNew;
google.maps.event.addListener(marker, 'dragstart', function() {
positionStart = this.position;
document.getElementById('start').innerHTML = "start position: " + positionStart.toUrlValue(6);
});
google.maps.event.addListener(marker, 'dragend', function() {
if (confirm("Are You Sure You Want To Move this marker?")) {
positionStartNew = this.position;
document.getElementById('end').innerHTML = "end position: " + positionStartNew.toUrlValue(6);
} else {
marker.setPosition(positionStart);
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
background-color: white;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="start"></div>
<div id="end"></div>
<div id="map"></div>
Based on my understanding, this is a possible solution:
google.maps.event.addListener(marker, 'dragend', function() {
if (confirm("Are You Sure You Want To Move this marker?")) {
var positionStartLatNew = this.position.lat();
var positionStartLngNew = this.position.lng();
document.getElementById('end').innerHTML = "Lat end : " +
positionStartLatNew + ", " + "Lng end : " + positionStartLngNew;
} else {
marker.setPosition(myLatlng);
}
});
Just change the code inside the else block so that the marker moves back to the original latLng position.
This is a JSBIN example
This is downloaded complete Javascript for google maps api that I'm customizing for my needs. What this code does is creating markers with popup info. The text in the content of the popus is from CSS file, with the following information: name, address1, address2 and postalCode. I need to add different images underneath the text info for each marker, I have added variable for image and assume it should add something like something like this "<img src=''>" in the var iwContent variable but i can not figure out how to
var map;
var infoWindow;
var markersData = [{
lat: 41.998079,
lng: 21.426156,
name: "Camping Praia da Barra",
address1: "Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré"
}];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.601203, -8.668173),
zoom: 9,
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
function displayMarkers() {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var name = markersData[i].name;
var address1 = markersData[i].address1;
var address2 = markersData[i].address2;
var postalCode = markersData[i].postalCode;
var image = markersData[i].image;
createMarker(latlng, name, address1, address2, postalCode, image);
bounds.extend(latlng);
}
map.fitBounds(bounds);
}
function createMarker(latlng, name, address1, address2, postalCode, image) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name,
icon: 'anchor_point_with shadow.png'
});
google.maps.event.addListener(marker, 'click', function() {
var iwContent = '<div id="iw_container">' + '<div class="iw_title">' + name + '</div>' + '<div class="iw_content">' + address1 + '<br />' + address2 + '<br />' + postalCode + '</div></div>'; //i guess change should be made at this line
infoWindow.setContent(iwContent);
infoWindow.open(map, marker);
});
}
Add an <img src="... to the string ìwContent including image, after defining it in markersData
var markersData = [{
lat: 41.998079,
lng: 21.426156,
name: "Camping Praia da Barra",
address1: "Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré",
image: "http://lorempixel.com/100/100/"
}];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.601203, -8.668173),
zoom: 9,
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
function displayMarkers() {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var name = markersData[i].name;
var address1 = markersData[i].address1;
var address2 = markersData[i].address2;
var postalCode = markersData[i].postalCode;
var image = markersData[i].image;
createMarker(latlng, name, address1, address2, postalCode, image);
bounds.extend(latlng);
}
map.fitBounds(bounds);
}
function createMarker(latlng, name, address1, address2, postalCode, image) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name,
//icon: 'anchor_point_with shadow.png'
});
google.maps.event.addListener(marker, 'click', function() {
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">' + name + '</div>' +
'<div class="iw_content">' + address1 + '<br />' +
address2 + '<br />' +
postalCode + '</div>'+
'<img src="'+image+'"></div>'; //i guess change should be made at this line
infoWindow.setContent(iwContent);
infoWindow.open(map, marker);
});
};
initialize();
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>
var markersData = [{
lat: 41.998079,
lng: 21.426156,
name: "Camping Praia da Barra",
address1: "Rua Diogo Cão, 125",
address2: "Praia da Barra",
postalCode: "3830-772 Gafanha da Nazaré",
image: "http://lorempixel.com/100/100/"
}];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.601203, -8.668173),
zoom: 9,
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
function displayMarkers() {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var name = markersData[i].name;
var address1 = markersData[i].address1;
var address2 = markersData[i].address2;
var postalCode = markersData[i].postalCode;
var image = markersData[i].image;
createMarker(latlng, name, address1, address2, postalCode, image);
bounds.extend(latlng);
}
map.fitBounds(bounds);
}
function createMarker(latlng, name, address1, address2, postalCode, image) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name,
//icon: 'anchor_point_with shadow.png'
});
google.maps.event.addListener(marker, 'click', function() {
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">' + name + '</div>' +
'<div class="iw_content">' + address1 + '<br />' +
address2 + '<br />' +
postalCode + '</div>'+
'<img src="'+image+'"></div>'; //i guess change should be made at this line
infoWindow.setContent(iwContent);
infoWindow.open(map, marker);
});
};
initialize();
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>
This javascript wont get the coordinates of the user
(this is a html, js and css application only)
(the area with Bold and Italic text, is the one supposed to get the coordinates from the client)
I have tried different soloutions, and they wont work, + it doesnt show the ones if the user is within 25km
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
<script type="text/javascript">
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
gmarkers.push(marker);
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
google.maps.event.addListener(map, 'click', find_closest_marker);
downloadUrl("markers.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var id = markers[i].getAttribute("id");
var sted = markers[i].getAttribute("sted");
var html="<b>"+sted+"</b><br>"+id;
var marker = createMarker(point,sted+" "+id,html);
}
markerCluster = new MarkerClusterer(map, gmarkers);
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
function find_closest_marker( event ) {
var closestMarker = -1;
var closestDistance = Number.MAX_VALUE;
for( i=0;i<gmarkers.length; i++ ) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
if ( distance < closestDistance ) {
closestMarker = i;
closestDistance = distance;
}
}
map.setCenter(gmarkers[closestMarker].getPosition());
if (map.getZoom() < 16) map.setZoom(16);
google.maps.event.trigger(gmarkers[closestMarker], 'click');
}
</script>
You can user a simple JS function for that.
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLatLng);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showLatLng(location) {
alert("Latitude: " + location.coords.latitude +
"Longitude: " + location.coords.longitude);
}
</script>
Hope it helps
I am plotting addresses and having an issue with the infowindow showing the right content everytime. Sometimes it shows the right content in the infowindow when clicked and sometimes it shows the wrong information for that map pin.
var map = null;
var markersArray = [];
var markers = [];
var openedInfoWindow ="";
var geocoder = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapInfoManual"),
mapOptions);
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom() > 20) // Change max/min zoom here
this.setZoom(18);
google.maps.event.removeListener(zoomChangeBoundsListener);
});
});
addMarker();
}
function addMarker() {
var bounds = new google.maps.LatLngBounds();
for(i=0; i<markersArray.length; i++)
{
CodeAddress(markersArray[i]['address']);
var mytitle = (markersArray[i]['title']);
var myaddress = (markersArray[i]['displayaddress']);
var linkurl = (markersArray[i]['linkurl']);
}
setTimeout(function()
{
for(i=0; i<markers.length; i++)
{
var point = new google.maps.LatLng(markers[i]['lat'], markers[i]['lng']);
var marker = new google.maps.Marker({
position: point,
map: map
});
bounds.extend(point);
var infoWindowContent = "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>"+ mytitle +"</div><div style='margin-bottom:5px;'>" + myaddress + "</div><div><a href='" + linkurl + "/'>More Details</a></div></div>";
openInfoWindow(marker,infoWindowContent)
}
map.fitBounds(bounds);
},2500);
}
// Address To Marker
function CodeAddress(address)
{
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
markers.push({
'lat':lat,
'lng':lng,
'address':address
});
}
});
}
//Info Window
function openInfoWindow(marker,infoWindowContent)
{
var infowindow = new google.maps.InfoWindow({
content: '<div class="cityMapInfoPop">'+infoWindowContent+'</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if(openedInfoWindow !="")
{
openedInfoWindow.close()
}
infowindow.open(map,marker);
openedInfoWindow = infowindow;
});
}
Variables that I pass in:
<script type="application/javascript">
markersArray.push({
"title":'<?php echo $maptitle;?>',
"address":'<?php echo $markerAddress;?>',
"displayaddress":'<?php echo $displayAddress;?>',
"linkurl":'<?php echo $addressUrl;?>'
});
</script>
Your issue is that geocoding is asynchronous. You loop through calling the geocoder on all your addresses, but the order the results are returned in is not predictable.
use function closure to associate the marker with the infowindow
use function closure to associate the address with the marker
use the results of the geocoder inside its callback function.
Note that if you have more that approximately 10 markers in your array you will run into the quota/rate limit of the geocoder.
proof of concept fiddle
code snippet:
var map = null;
var markersArray = [];
var markers = [];
var openedInfoWindow = "";
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
markersArray.push({
"title": 'marker 0',
"address": 'New York,NY',
"displayaddress": 'New York, NY',
"linkurl": 'http://google.com'
});
markersArray.push({
"title": 'marker 1',
"address": 'Boston, MA',
"displayaddress": 'Boston, MA',
"linkurl": 'http://yahoo.com'
});
markersArray.push({
"title": 'marker 2',
"address": 'Newark,NJ',
"displayaddress": 'Newark, NJ',
"linkurl": 'http://mapquest.com'
});
google.maps.event.addDomListener(window, "load", initialize);
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapInfoManual"),
mapOptions);
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom() > 20) // Change max/min zoom here
this.setZoom(18);
google.maps.event.removeListener(zoomChangeBoundsListener);
});
});
addMarker();
}
function addMarker() {
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markersArray.length; i++) {
CodeAddress(markersArray[i]);
}
}
// Address To Marker
function CodeAddress(markerEntry) {
var mytitle = (markerEntry['title']);
var myaddress = (markerEntry['displayaddress']);
var linkurl = (markerEntry['linkurl']);
geocoder.geocode({
'address': markerEntry['address']
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
bounds.extend(marker.getPosition());
var infoWindowContent = "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>" + mytitle + "</div><div style='margin-bottom:5px;'>" + myaddress + "</div><div><a href='" + linkurl + "/'>More Details</a></div></div>";
openInfoWindow(marker, infoWindowContent);
markers.push(marker);
map.fitBounds(bounds);
} else {
alert("geocode failed: " + status);
}
});
}
//Info Window
function openInfoWindow(marker, infoWindowContent) {
var infowindow = new google.maps.InfoWindow({
content: '<div class="cityMapInfoPop">' + infoWindowContent + '</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if (openedInfoWindow != "") {
openedInfoWindow.close();
}
infowindow.open(map, marker);
openedInfoWindow = infowindow;
});
}
html,
body,
#mapInfoManual {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?ext=.js"></script>
<div id="mapInfoManual" style="border: 2px solid #3872ac;"></div>
Since you didn't provide a working JSFiddle, it was rather difficult to figure out what your problem is. That said, you can look at this JSFiddle that I made for you to review what I'm doing, vs what you're doing.
Why are you using setTimeout() to place your markers? Also, you may have better results if you create an individual infoWindow per marker, instead of using a "global" infoWindow (which is what it looks like you're doing).
If you edit your post to add a working example of your problem, I can help further.
window.places = [{
title: "foo",
address: {
lat: parseFloat("64.85599578876611"),
lng: parseFloat("-147.83363628361917")
},
displayAddress: "101 BLVD",
linkURL: "google.com"
}, {
title: "bar",
address: {
lat: parseFloat("62.85599578876611"),
lng: parseFloat("-147.83363628361917")
},
displayAddress: "202 BLVD",
linkURL: "images.google.com"
}, ]
function initialize() {
"use strict";
var myLatlng = new google.maps.LatLng(window.places[0].address.lat, window.places[0].address.lng),
mapOptions = {
zoom: 4,
center: myLatlng
};
window.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
$.each(window.places, function(i) {
var infowindow = new google.maps.InfoWindow({
content: "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>" + window.places[i].title + "</div><div style='margin-bottom:5px;'>" + window.places[i].displayAddress + "</div><div><a href='" + window.places[i].linkURL + "/'>More Details</a></div></div>"
}),
marker = new google.maps.Marker({
position: new google.maps.LatLng(window.places[i].address.lat, window.places[i].address.lng),
map: window.map,
title: window.places[i].title
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(window.map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 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?v=3.exp&signed_in=true"></script>
<div id="map-canvas"></div>