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>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm working on a view of the ASP.NET, using mvc. I using google maps with different markers. Each of those markers have their own infowindows that have 3 buttons each. By clicking a specific button I want the marker to change color. How can I do that?
I have already tried using document.getElementById and using the addEventListner. I also tried to program the button by using the onclick function.
var locations = [
["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg", ],
["Aceite", "15/08/2019",38.817562, -8.941728, 36, "foto.jpg"],
["Em avaliação", "20/07/2019",38.487978, -9.004425, 90,"foto.jpg"],
["Concluído", "01/07/2019",37.045804, -8.898041, 12, "foto.jpg"]
];
var infowindow = new google.maps.InfoWindow({});
function setMarkers(map) {
for (var i = 0; i < locations.length; i++) {
var fire = locations[i];
var marker ;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<div id="bodyContent">' +
'<p><b>Avaliação da Ocorrência:</b></p>' +
'<p>Fotografias:' + fire[5] + '</p>' +
'<p>Avaliação:' + fire[0] + '</p>' +
'<p>Data:' + fire[1] + '</p></br>' +
'<button id="aceite">Aceite</button>' +
'<button>Recusado</button>' +
'<button> Em avaliação</button>' +
'<button> Concluído</button>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({ content: contentString });
marker = new google.maps.Marker({
position: { lat: fire[2], lng: fire[3] },
map: map,
info: contentString,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.info);
infoWindow.open(map, this);
});
}
}
The buttons are represented in the variable contentString, and when I click the button with the id "Aceite", I want to change the color of the marker to green.
Attempt to change the marker to green:
<button id="aceite" onclick="state(marker)">Aceite</button>
function state(marker){
marker.setIcon('google.com/mapfiles/marker_green.png');
}
Simplest would be to add the click listener function when you open the InfoWindow (when you know what marker it is associated with).
Add the click listener to the button when the domready event of the InfoWindow fires (and it has been added to the DOM):
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
Use function closure on the marker in the marker click listener (this references the marker in the click event listener function, but not in the InfoWindow domready event listener, save it so you can use it there):
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
infoWindow.setContent(this.info);
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
infoWindow.open(map, this);
});
proof of concept fiddle
code snippet:
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var infowindow = new google.maps.InfoWindow({});
setMarkers(map);
}
var locations = [
["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg", ],
["Aceite", "15/08/2019", 38.817562, -8.941728, 36, "foto.jpg"],
["Em avaliação", "20/07/2019", 38.487978, -9.004425, 90, "foto.jpg"],
["Concluído", "01/07/2019", 37.045804, -8.898041, 12, "foto.jpg"]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var fire = locations[i];
var marker;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<div id="bodyContent">' +
'<p><b>Avaliação da Ocorrência:</b></p>' +
'<p>Fotografias:' + fire[5] + '</p>' +
'<p>Avaliação:' + fire[0] + '</p>' +
'<p>Data:' + fire[1] + '</p></br>' +
'<button id="aceite">Aceite</button>' +
'<button>Recusado</button>' +
'<button> Em avaliação</button>' +
'<button> Concluído</button>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker = new google.maps.Marker({
position: {
lat: fire[2],
lng: fire[3]
},
map: map,
info: contentString,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
infoWindow.setContent(this.info);
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
infoWindow.open(map, this);
});
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
I have a set of markers and polygons displayed on my map, each marker and polygon is stored in a separate array. Currently, I have infowindows tied to my markers and I wanted to add infowindows to my polygons in case the user clicks on them. The marker infowindows work perfectly.
The problem is that when you click on the polygon the infowindow won't pop up unless you've clicked on a marker first. Then, the polygon infowindow will appear on the last clicked marker.
I've worked through every line of relevant code. I think the problem exists in that the infowindow is tied specifically to the marker icons, but I don't know how to detach it. I'm relatively new to JS and this is my first major on-going project.
var map;
var mapCenter = { lat: 28.201890, lng: -81.027334 };
var mPoint = "/images/placemark_circle_highlight.png";
var locations = [];
var locationsPoly = [];
var markers = [];
var infos = [];
var polygons = [];
var polyInfos = [];
var infowindow;
var testInfoWindow1 =
'<div id="content">' +
'<h1 class="header">Test Marker #1</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 1.</p>" +
"</div>" +
"</div>";
var testInfoWindow2 =
'<div id="content">' +
'<h1 class="header">Test Marker #2</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 2.</p>" +
"</div>" +
"</div>";
var testInfoWindow3 =
'<div id="content">' +
'<h1 class="header">Test Marker #3</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 3.</p>" +
"</div>" +
"</div>";
var testInfoWindow4 =
'<div id="content">' +
'<h1 class="header">Test Marker #4</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 4.</p>" +
"</div>" +
"</div>";
var testInfoWindow5 =
'<div id="content">' +
'<h1 class="header">Test Marker #5</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 5.</p>" +
"</div>" +
"</div>";
var pOneDesc =
'<div id="content">' +
'<h1 class="header">#1 Polygon Window</h1>' +
'<div class="desc">' +
"<p>Lorem.</p>" +
"</div>" +
"</div>";
var pTwoDesc =
'<div id="content">' +
'<h1 class="header">#2 Polygon Window</h1>' +
'<div class="desc">' +
"<p>elementum pulvinar etiam.</p>" +
"</div>" +
"</div>";
var pThreeDesc =
'<div id="content">' +
'<h1 class="header">#3 Polygon Window</h1>' +
'<div class="desc">' +
"<p>orci eu lobortis elementum nibh tellus molestie.</p>" +
"</div>" +
"</div>";
function initMap() {
var myOptions = {
zoom: 15,
center: mapCenter,
mapTypeControl: true,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.TERRAIN,
};
map = new google.maps.Map(document.getElementById("map"),
myOptions);
locations = [
["Test Marker #1", 28.210862, -81.038192, testInfoWindow1, mPoint, 'category1'],
["Test Marker #2", 28.206477, -81.016176, testInfoWindow2, mPoint, 'category1'],
["Test Marker #3", 28.216659, -81.029092, testInfoWindow3, mPoint, 'category1'],
["Test Marker #4", 28.195328, -81.044638, testInfoWindow4, mPoint, 'category1'],
["Test Marker #5", 28.196439, -81.006932, testInfoWindow5, mPoint, 'category1']
];
var polygonOne = [
[28.187985, -81.045365],
[28.183579, -81.045365],
[28.183579, -81.041156],
[28.187922, -81.041341]
];
var pointsPolyOne = [];
for (var i = 0; i < polygonOne.length; i++) {
pointsPolyOne.push({
lat: polygonOne[i][0],
lng: polygonOne[i][1]
});
}
var polygonTwo = [
[28.185258, -81.033373],
[28.183601, -81.030751],
[28.187809, -81.026072]
];
var pointsPolyTwo = [];
for (var i = 0; i < polygonTwo.length; i++) {
pointsPolyTwo.push({
lat: polygonTwo[i][0],
lng: polygonTwo[i][1]
});
}
var polygonThree = [
[28.189691, -81.032381],
[28.188111, -81.032337],
[28.188291, -81.031608],
[28.189719, -81.031276]
];
var pointsPolyThree = [];
for (var i = 0; i < polygonThree.length; i++) {
pointsPolyThree.push({
lat: polygonThree[i][0],
lng: polygonThree[i][1]
});
}
locationsPoly = [
[pointsPolyThree, pOneDesc, "#f44336", 0.8, 2, "#ffffff", 0.35, 'FY19'],
[pointsPolyTwo, pTwoDesc, "#4caf50", 0.8, 2, "#bdeabf", 0.35, 'FY19'],
[pointsPolyOne, pThreeDesc, "#849199", 0.8, 2, "#ffffff", 0.35, 'FY19']
];
infowindow = new google.maps.InfoWindow();
setMarkers(map, locations);
setPolygons(map, locationsPoly);
}
function setMarkers(map, locations) {
var marker, i
for (i = 0; i < locations.length; i++) {
var title = locations[i][0];
var lat = locations[i][1];
var long = locations[i][2];
var desc = locations[i][3];
var pin = locations[i][4];
var category = locations[i][5];
latlngset = new google.maps.LatLng(lat, long);
marker = new google.maps.Marker({
map: map,
title: title,
position: latlngset,
icon: pin,
category: category
});
marker.mycategory = category;
marker.myname = name;
markers.push(marker);
var content = desc;
google.maps.event.addListener(marker, 'click', (function (marker, content) {
return function () {
/* close the previous info-window */
closeInfos();
infowindow.setContent(content);
infowindow.setPosition(event.latlng);
infowindow.open(map, marker);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(marker, content));
google.maps.event.addListener(map, "click", function (marker, content) {
closeInfos();
});
}
}
function setPolygons(map, locationsPoly) {
var polygon, i
for (i = 0; i < locationsPoly.length; i++) {
var paths = locationsPoly[i][0];
var polyDesc = locationsPoly[i][1];
var strokeColor = locationsPoly[i][2];
var strokeOpacity = locationsPoly[i][3];
var strokeWeight = locationsPoly[i][4];
var fillColor = locationsPoly[i][5];
var fillOpacity = locationsPoly[i][6];
var categoryPoly = locationsPoly[i][7];
polygon = new google.maps.Polygon({
map: map,
paths: paths,
strokeColor: strokeColor,
strokeOpacity: strokeOpacity,
strokeWeight: strokeWeight,
fillColor: fillColor,
fillOpacity: fillOpacity,
category: categoryPoly
});
polygon.mycategory = categoryPoly;
polygon.myname = name;
polygons.push(polygon);
var polyContent = polyDesc;
google.maps.event.addListener(polygon, 'click', (function (polygon, polyContent) {
return function () {
/* close the previous info-window */
closeInfos();
infowindow.setContent(polyContent);
infowindow.setPosition(getHighestWindowPosition(paths));
infowindow.open(map, polygon);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(polygon, polyContent));
google.maps.event.addListener(map, "click", function (marker, content) {
closeInfos();
});
}
}
function getHighestWindowPosition(paths) {
var lat = -5000, lng = 0, i = 0, n = paths.length;
for (; i !== n; ++i) {
if (paths[i].lat > lat) {
lat = paths[i].lat;
lng = paths[i].lng;
}
}
return { lat: lat, lng: lng };
}
function closeInfos() {
if (infos.length > 0) {
/* detach the info-window from the marker ... undocumented in the API docs */
infos[0].set("marker", "polygon", null);
/* and close it */
infos[0].close();
/* blank the array */
infos.length = 0;
}
}
<!DOCTYPE html>
<html>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<head>
<title>Test Map for Markers-Polygons</title>
<script type="application/javascript" src="js/checkbox.js?rndstr=<%= getRandomStr() %>"></script>
<style>
#map {
height: 100vh;
}
html,
body {
height: 100vh;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=##APIKEYHERE##&callback=initMap"
async defer></script>
</body>
</html>
UPDATE: Minimum reproducible example.
The infowindow now appears on a polygon, but only the first one in the array.
Two issues remain.
Per my comment, and the related question: Open InfoWindow for each polygon google maps V3, the InfoWindow.open method's second parameter (if it exists) must be an "anchor" (with a position property), which a google.maps.Polygon object is not.
infowindow.open(map, polygon);
should be:
infowindow.open(map);
You are using the paths variable inside the "click" event listener function, but you don't have function closure on it (you only have function closure on polygon and polygonContent).
google.maps.event.addListener(polygon, 'click', (function (polygon, polyContent) {
return function () {
/* close the previous info-window */
closeInfos();
infowindow.setContent(polyContent);
infowindow.setPosition(getHighestWindowPosition(paths));
infowindow.open(map, polygon);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(polygon, polyContent));
should be:
google.maps.event.addListener(polygon, 'click', (function (polygon, polyContent, paths) {
return function (evt) {
/* close the previous info-window */
closeInfos();
infowindow.setContent(polyContent);
infowindow.setPosition(getHighestWindowPosition(paths));
infowindow.open(map);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(polygon, polyContent, paths));
proof of concept fiddle
code snippet:
var map;
var mapCenter = {
lat: 28.201890,
lng: -81.027334
};
var mPoint = "/images/placemark_circle_highlight.png";
var locations = [];
var locationsPoly = [];
var markers = [];
var infos = [];
var polygons = [];
var polyInfos = [];
var infowindow;
var testInfoWindow1 =
'<div id="content">' +
'<h1 class="header">Test Marker #1</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 1.</p>" +
"</div>" +
"</div>";
var testInfoWindow2 =
'<div id="content">' +
'<h1 class="header">Test Marker #2</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 2.</p>" +
"</div>" +
"</div>";
var testInfoWindow3 =
'<div id="content">' +
'<h1 class="header">Test Marker #3</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 3.</p>" +
"</div>" +
"</div>";
var testInfoWindow4 =
'<div id="content">' +
'<h1 class="header">Test Marker #4</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 4.</p>" +
"</div>" +
"</div>";
var testInfoWindow5 =
'<div id="content">' +
'<h1 class="header">Test Marker #5</h1>' +
'<div class="desc">' +
"<p>This is a marker at position number 5.</p>" +
"</div>" +
"</div>";
var pOneDesc =
'<div id="content">' +
'<h1 class="header">#1 Polygon Window</h1>' +
'<div class="desc">' +
"<p>Lorem.</p>" +
"</div>" +
"</div>";
var pTwoDesc =
'<div id="content">' +
'<h1 class="header">#2 Polygon Window</h1>' +
'<div class="desc">' +
"<p>elementum pulvinar etiam.</p>" +
"</div>" +
"</div>";
var pThreeDesc =
'<div id="content">' +
'<h1 class="header">#3 Polygon Window</h1>' +
'<div class="desc">' +
"<p>orci eu lobortis elementum nibh tellus molestie.</p>" +
"</div>" +
"</div>";
function initMap() {
var myOptions = {
zoom: 13,
center: mapCenter,
mapTypeControl: true,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.TERRAIN,
};
map = new google.maps.Map(document.getElementById("map"),
myOptions);
locations = [
["Test Marker #1", 28.210862, -81.038192, testInfoWindow1, mPoint, 'category1'],
["Test Marker #2", 28.206477, -81.016176, testInfoWindow2, mPoint, 'category1'],
["Test Marker #3", 28.216659, -81.029092, testInfoWindow3, mPoint, 'category1'],
["Test Marker #4", 28.195328, -81.044638, testInfoWindow4, mPoint, 'category1'],
["Test Marker #5", 28.196439, -81.006932, testInfoWindow5, mPoint, 'category1']
];
var polygonOne = [
[28.187985, -81.045365],
[28.183579, -81.045365],
[28.183579, -81.041156],
[28.187922, -81.041341]
];
var pointsPolyOne = [];
for (var i = 0; i < polygonOne.length; i++) {
pointsPolyOne.push({
lat: polygonOne[i][0],
lng: polygonOne[i][1]
});
}
var polygonTwo = [
[28.185258, -81.033373],
[28.183601, -81.030751],
[28.187809, -81.026072]
];
var pointsPolyTwo = [];
for (var i = 0; i < polygonTwo.length; i++) {
pointsPolyTwo.push({
lat: polygonTwo[i][0],
lng: polygonTwo[i][1]
});
}
var polygonThree = [
[28.189691, -81.032381],
[28.188111, -81.032337],
[28.188291, -81.031608],
[28.189719, -81.031276]
];
var pointsPolyThree = [];
for (var i = 0; i < polygonThree.length; i++) {
pointsPolyThree.push({
lat: polygonThree[i][0],
lng: polygonThree[i][1]
});
}
locationsPoly = [
[pointsPolyThree, pOneDesc, "#f44336", 0.8, 2, "#ffffff", 0.35, 'FY19'],
[pointsPolyTwo, pTwoDesc, "#4caf50", 0.8, 2, "#bdeabf", 0.35, 'FY19'],
[pointsPolyOne, pThreeDesc, "#849199", 0.8, 2, "#ffffff", 0.35, 'FY19']
];
infowindow = new google.maps.InfoWindow();
setMarkers(map, locations);
setPolygons(map, locationsPoly);
}
function setMarkers(map, locations) {
var marker, i
for (i = 0; i < locations.length; i++) {
var title = locations[i][0];
var lat = locations[i][1];
var long = locations[i][2];
var desc = locations[i][3];
var pin = locations[i][4];
var category = locations[i][5];
latlngset = new google.maps.LatLng(lat, long);
marker = new google.maps.Marker({
map: map,
title: title,
position: latlngset,
// icon: pin,
category: category
});
marker.mycategory = category;
marker.myname = name;
markers.push(marker);
var content = desc;
google.maps.event.addListener(marker, 'click', (function(marker, content) {
return function() {
/* close the previous info-window */
closeInfos();
infowindow.setContent(content);
infowindow.setPosition(event.latlng);
infowindow.open(map, marker);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(marker, content));
google.maps.event.addListener(map, "click", function(marker, content) {
closeInfos();
});
}
}
function setPolygons(map, locationsPoly) {
var polygon, i
for (i = 0; i < locationsPoly.length; i++) {
var paths = locationsPoly[i][0];
var polyDesc = locationsPoly[i][1];
var strokeColor = locationsPoly[i][2];
var strokeOpacity = locationsPoly[i][3];
var strokeWeight = locationsPoly[i][4];
var fillColor = locationsPoly[i][5];
var fillOpacity = locationsPoly[i][6];
var categoryPoly = locationsPoly[i][7];
polygon = new google.maps.Polygon({
map: map,
paths: paths,
strokeColor: strokeColor,
strokeOpacity: strokeOpacity,
strokeWeight: strokeWeight,
fillColor: fillColor,
fillOpacity: fillOpacity,
category: categoryPoly
});
polygon.mycategory = categoryPoly;
polygon.myname = name;
polygons.push(polygon);
var polyContent = polyDesc;
google.maps.event.addListener(polygon, 'click', (function(polygon, polyContent, paths) {
return function(evt) {
/* close the previous info-window */
closeInfos();
infowindow.setContent(polyContent);
infowindow.setPosition(getHighestWindowPosition(paths));
infowindow.open(map);
/* keep the handle, in order to close it on next click event */
infos[0] = infowindow;
};
})(polygon, polyContent, paths));
google.maps.event.addListener(map, "click", function(marker, content) {
closeInfos();
});
}
}
function getHighestWindowPosition(paths) {
console.log(paths);
var lat = -5000,
lng = 0,
i = 0,
n = paths.length;
for (; i !== n; ++i) {
if (paths[i].lat > lat) {
lat = paths[i].lat;
lng = paths[i].lng;
}
}
console.log("lat=" + lat + " lng=" + lng);
return {
lat: lat,
lng: lng
};
}
function closeInfos() {
if (infos.length > 0) {
/* detach the info-window from the marker ... undocumented in the API docs */
infos[0].set("marker", "polygon", null);
/* and close it */
infos[0].close();
/* blank the array */
infos.length = 0;
}
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
I have searched all over this site to find an answer with no luck. I have an array of lat, and lng markers and I'd like to open an info window based on the array index. I got it to work by replacing markers with variables instead of an array list, but I want to keep my code DRY. Here is my code:
function initMap() {
var locations = [
["blairCountyPA", 40.453132, -78.384223],
["scrantonPA", 41.408969, -75.662412],
["warringtonTownshipPA", 40.250319, -75.166212],
["lancasterCountyPA", 40.046657, -76.178374],
["berkeleyCountyWV", 39.488560, -78.065193],
["bowieMD", 39.006777, -76.779136],
["anneArundelCountyMD", 38.953011, -76.548823],
["shenandoahVA", 38.483457, -78.849748],
["calvertCountyMD", 38.494950, -76.502574],
["salsiburyMD", 38.360674, -75.599369],
["berlinMD", 38.322615, -75.217689],
["ocMD", 38.336503, -75.084906],
["lynchburgVA", 37.413754, -79.142246]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(39.488560, -78.065193)
});
for(var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
icon: 'images/pin-cloud.png',
animation: google.maps.Animation.DROP,
map: map
});
}
var blairCountyContentString =
'<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Blair County, PA</h1>'+
'<div id="bodyContent">'+
"<p>insert info here</p>" +
'<p><b>Resources</b>: <a href="https://efc.umd.edu/assets/sw_case_studies/blair_county_final.pdf" <span>Case Study Blair County, PA</span> </a></p>'+
'</div>'+
'</div>';
var blairCountyInfowindow = new google.maps.InfoWindow({
content: blairCountyContentString,
position: locations[0]
});
marker.addListener('click', function() {
blairCountyInfowindow.open(map, marker);
});
My issue seems to be with the "position: locations[0]" object literal. Sometimes I get an error stating that this needs to be a number value of lng, lat...Tried it though with no luck. The window currently opens but only for the last index of the array. Any ideas?
See updated Code. Now customize the infowindow content
Fiddle link
function initMap() {
var marker = [];
var locations = [
["blairCountyPA", 40.453132, -78.384223],
["scrantonPA", 41.408969, -75.662412],
["warringtonTownshipPA", 40.250319, -75.166212],
["lancasterCountyPA", 40.046657, -76.178374],
["berkeleyCountyWV", 39.488560, -78.065193],
["bowieMD", 39.006777, -76.779136],
["anneArundelCountyMD", 38.953011, -76.548823],
["shenandoahVA", 38.483457, -78.849748],
["calvertCountyMD", 38.494950, -76.502574],
["salsiburyMD", 38.360674, -75.599369],
["berlinMD", 38.322615, -75.217689],
["ocMD", 38.336503, -75.084906],
["lynchburgVA", 37.413754, -79.142246]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(39.488560, -78.065193)
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
var ContentString =
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">' + locations[i][0] + '</h1>' +
'<div id="bodyContent">' +
"<p>insert info here</p>" +
'<p><b>Resources</b>: <a href="https://efc.umd.edu/assets/sw_case_studies/blair_county_final.pdf" <span>Case Study ' + locations[i][0] + '</span> </a></p>' +
'</div>' +
'</div>';
return function() {
infowindow.setContent(ContentString);
infowindow.open(map, marker);
}
})(marker, i));
}
}
I want to my pin to change color when I click on it in google maps.
I have the below code, the color changes but I want it to revert back to the original when the infowindow is closed. see fiddle
Where am I going wrong here?
<div id="map_canvas"></div>
var mylatlongs = [
{"rank":1,"name":"name 1","lat":"-25.901820984476252","lng":"135"},
{"rank":2,"name":"name 2","lat":"-25.901820984476252","lng":"135.05"},
{"rank":3,"name":"name 3","lat":"-25.901820984476252","lng":"135.025"}
];
var infowindow = null;
jQuery(function() {
var StartLatLng = new google.maps.LatLng(mylatlongs[0]['lat'], mylatlongs[0]['lng']);
var mapOptions = {
center: StartLatLng,
streetViewControl: false,
panControl: false,
maxZoom:17,
zoom : 13,
zoomControl:true,
zoomControlOptions: {
style:google.maps.ZoomControlStyle.SMALL
}
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var infowindow = new google.maps.InfoWindow({
content: ''
});
jQuery.each( mylatlongs, function(i, m) {
var StartLatLng = new google.maps.LatLng(-25.901820984476252, 134.00135040279997);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(m.lat, m.lng),
bounds: true,
id : 'mk_' + m.rank,
letter : m.index,
map: map,
title: m.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
infowindow.setContent(contentString);
infowindow.open(map,marker);
marker.setIcon('https://www.google.com/mapfiles/marker_green.png');
});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+ m.name + '</h1>'+
'<div id="bodyContent">'+ (m.rank) +
'</div>'+
'</div>';
});
});
#map_canvas {
float: left;
height: 565px;
width: 100%;
}
#content {
min-width: 320px;
}
You don't track which marker has infowindow open. One possible solution is to add global variable which will contain information about marker with opened infowindow:
var infowindow = null;
var markerRed;
And change icon to red color when marker is clicked:
google.maps.event.addListener(marker, 'click', function() {
if (markerRed) {
markerRed.setIcon('https://www.google.com/mapfiles/marker.png');
}
infowindow.close();
infowindow.setContent(contentString);
infowindow.open(map,marker);
marker.setIcon('https://www.google.com/mapfiles/marker_green.png');
markerRed = marker;
});
Update: icon change on close of infowindow:
var infowindow = new google.maps.InfoWindow({
content: ''
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
if (markerRed) {
markerRed.setIcon('https://www.google.com/mapfiles/marker.png');
}
});