I have json data, i want to display LatLng data on map. Now the given LatLng was displayed on map but I am not getting infoWindow when i click, please help. I have attaced my code below : here is my script tag.
Please suggess me how to do this, once again thank you
<script>
var obj = {
"location": [
{
"street_address": {
"city": "Trichy",
"state": "TamilNadu",
"address_1": "Test address",
"country": "India"
},
"gps": {
"latitude": 32.67,
"longitude": -85.44
}
},
{
"street_address": {
"city": "Madurai",
"state": "TamilNadu",
"address_1": "Test address",
"country": "India"
},
"gps": {
"latitude": 28.65859029,
"longitude": 77.22063432
}
},
{
"street_address": {
"city": "Chennai",
"state": "TamilNadu",
"address_1": "Test address",
"country": "India"
},
"gps": {
"latitude": 67.1,
"longitude": -157.85
}
},
{
"street_address": {
"city": "Combiatore",
"state": "TamilNadu",
"address_1": "Test address",
"country": "India"
},
"gps": {
"latitude": 52.67,
"longitude": -95.44
}
},
{
"street_address": {
"city": "Tirunelveli",
"state": "TamilNadu",
"address_1": "Test address",
"country": "India"
},
"gps": {
"latitude": 25.9,
"longitude": -97.43
}
}
]
};
var place = [];
var locations = [];
for(var i = 0; i < obj["location"].length;i++){
//var data = {"latitude" : 0, "longitude" : 0};
//data["latitude"] = obj["location"][i]["gps"]
locations.push(obj["location"][i]["gps"]);
place.push(obj["location"][i]["street_address"]);
}
console.log(place);
console.log(locations);
var pointer = new google.maps.LatLng(51.508742,-0.120850);
function intialize(){
var mapOption = {
zoom : 3,
center : pointer,
mapTypeControl:true,
mapTypeControlOptions: {
style:google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOption);
for(var i = 0; i < locations.length; i++){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]["latitude"], locations[i]["longitude"]),
icon: 'map-icon.png'
});
marker.setMap(map);
console.log(locations[i]["latitude"], locations[i]["longitude"]);
}
for(var i = 0;i < place.length; i++){
var infoWindow = new google.maps.InfoWindow({
content : new google.maps.InfoWindow(place[i]["address_1"], place[i]["city"],place[i]["country"],place[i]["state"])
});
google.maps.event.addListener(marker, 'click', function(){
infoWindow.open(map, marker);
});
console.log(place[i]["address_1"], place[i]["city"],place[i]["country"],place[i]["state"]);
}
}
google.maps.event.addDomListener(window, 'load', intialize);
</script>
There are multiple issues with your code.
The for Loops
In the second for loop where you're iterating over the place array you're accessing the variable marker and expect it to be the place's marker. The marker variable is, however, only updated in the for loop before where you're iterating over the locations array.
for(var i = 0; i < locations.length; i++){
var marker = new google.maps.Marker(...);
...
}
for(var i = 0;i < place.length; i++){
...
google.maps.event.addListener(marker, ...);
// Here marker will always be the last marker that
// was created in the preceding loop
}
To correct this, combine the two loops.
for(var i = 0; i < locations.length; i++){
var marker = new google.maps.Marker(...);
...
google.maps.event.addListener(marker, ...);
// Here marker will be the current location's marker
}
The InfoWindow Constructor
You're not calling the google.maps.InfoWindow constructor correctly since you're specifying another InfoWindow for the contentparameter.
var infoWindow = new google.maps.InfoWindow({
content : new google.maps.InfoWindow(...)
});
The API does, however, expect content to be a string (plain text or HTML) containing, guess what, the info window's content.
var infoWindow = new google.maps.InfoWindow({
content : '<div>Hello, I am an info window</div>'
});
The for Loop's Scope
Finally, the for loop does not create a new scope that means the current values of your local variables (like marker) are not wrapped with the click event-handler. Hence, accessing those variables in the handler function will yield their values after the for loop has finished.
for(var i = 0; i < locations.length; i++){
var marker = new google.maps.Marker(...);
...
google.maps.event.addListener(marker, 'click', function(){
infoWindow.open(map, marker);
// At the time of click the for loop has finished.
// Thus, marker will be the last marker that was created in the loop.
});
}
You can work around this by wrapping the handler in a function closure. Oh and, by the way, you'll only need a single instance of InfoWindow.
var infoWindow = new google.maps.InfoWindow();
for(var i = 0; i < locations.length; i++){
var marker = new google.maps.Marker(...);
...
google.maps.event.addListener(marker, 'click', (function(marker, i){
return function() {
infoWindow.close();
infoWindow.setContent("<div>" + place[i]["city"] + "</div>");
infoWindow.open(map, marker);
// You could also use this instead of marker here but you'll
// still need the closure for i
}
})(marker, i)); // Pass in marker and i to make the closure work
}
Wrapping Up
A somewhat simplified version of your corrected initialize function looks like this (JSFiddle).
function intialize(){
var mapOption = {
zoom : 3,
center : pointer,
mapTypeControl:true,
mapTypeControlOptions: {
style:google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOption);
var infoWindow = new google.maps.InfoWindow();
for(var i = 0; i < locations.length; i++){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]["latitude"], locations[i]["longitude"])
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', (function(marker, i){
return function() {
infoWindow.close();
infoWindow.setContent("<div>" + place[i]["city"] + "</div>");
infoWindow.open(map, this);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', intialize);
Only copying the relevant code here. I have changed the place of infoWindow marker instance creation. Each infoWindow object will be attached to marker due to closure. Check if this is working for you.
function intialize(){
var mapOption = {
zoom : 3,
center : pointer,
mapTypeControl:true,
mapTypeControlOptions: {
style:google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOption);
for(var i = 0; i < locations.length; i++){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]["latitude"], locations[i]["longitude"]),
icon : 'map-icon.png'
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', (function(){
return function(){
var infoWindow = new google.maps.InfoWindow({
content : new google.maps.InfoWindow(place[i]["address_1"], place[i]["city"],place[i]["country"],place[i]["state"])
});
infoWindow.open(map, marker);
}
})());
}
}
Related
I'm trying to draw route between source and destination with multiple stops using Google Maps API. I'll pass lat and log values for source, destination and all the stops.I've tried using the basic snippet but theat code (below) a route is drawn between each stops.
[![<script type="text/javascript">
var markers = [
{
"timestamp": 'Alibaug',
"latitude": '18.641400',
"longitude": '72.872200',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
},
{
"timestamp": 'Mumbai',
"latitude": '18.964700',
"longitude": '72.825800',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}
,
{
"timestamp": 'Pune',
"latitude": '18.523600',
"longitude": '73.847800',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
\];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers\[0\].latitude, markers\[0\].longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers\[i\]
var myLatlng = new google.maps.LatLng(data.latitude, data.longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.timestamp
});
// console.log(i)
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.timestamp);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng\[i\];
var des = lat_lng\[i + 1\];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.WALKING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes\[0\].overview_path.length; i < len; i++) {
path.push(result.routes\[0\].overview_path\[i\]);
}
}
});
}
}
}
</script>][1]][1]
In the above image, there is an extra route drawn.
fiddle demonstrating issue with more points
You have a typo/bug in your code. Remove this line:
path.push(src);
from this loop:
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
// path.push(src); <============================================ here
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.WALKING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
a second problem comes from the asynchronous nature of the directions service. The order of the responses from the service is not guaranteed to be in the same order as the requests are sent. The simplest way to fix that is to create a separate polyline for each result:
function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({
map: map,
strokeColor: '#4986E7'
});
poly.setPath(path);
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
proof of concept fiddle
code snippet:
var markers = [{
"timestamp": 'Alibaug',
"latitude": '18.641400',
"longitude": '72.872200',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
},
{
"timestamp": 'Mumbai',
"latitude": '18.964700',
"longitude": '72.825800',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
},
{
"timestamp": 'Pune',
"latitude": '18.523600',
"longitude": '73.847800',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
},
{
"timestamp": 'Bhopal',
"latitude": '23.2599',
"longitude": '73.857800',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
},
{
"timestamp": 'Bhopal',
"latitude": '26.9124',
"longitude": '75.7873',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
];
window.onload = function() {
var mapOptions = {
center: new google.maps.LatLng(markers[0].latitude, markers[0].longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.latitude, data.longitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.timestamp
});
// console.log(i)
latlngbounds.extend(marker.position);
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.timestamp);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Direction Service
var service = new google.maps.DirectionsService();
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
// path.push(src);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.WALKING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({
map: map,
strokeColor: '#4986E7'
});
poly.setPath(path);
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#dvMap {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="dvMap"></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 am trying to learn from a simple google developers tutorial in import GeoJSON data from either a local or remote source, and display it on my map. I have code and this code for USGS earth quake data JSON:
<!DOCTYPE html>
<html>
<head>
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(2.8,-187.3),
mapTypeId: 'terrain'
});
// Create a <script> tag and set the USGS URL as the source.
var script = document.createElement('script');
// This example uses a local copy of the GeoJSON stored at
// http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
script.src = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp';
document.getElementsByTagName('head')[0].appendChild(script);
}
// Loop through the results array and place a marker for each
// set of coordinates.
window.eqfeed_callback = function(results) {
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var text = ''+results.features[i].properties.place+'';
var latLng = new google.maps.LatLng(coords[1],coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
var infowindow = new google.maps.InfoWindow({
content: text
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=xxxx&callback=initMap">
</script>
</body>
</html>
The code working fine without problem. But I am having some problems with InfoWindows when clicked on marker's should open and hold some information. I try to configure it but it doesn't work. When clicked no opening on the marker's click event that I attached example like place name for that earth quake.
JSON response for earth quake:
{
"type": "FeatureCollection",
"metadata": {
"generated": 1545674780000,
"url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp",
"title": "USGS Magnitude 2.5+ Earthquakes, Past Week",
"status": 200,
"api": "1.7.0",
"count": 326
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 2.6,
"place": "14km WNW of Big Lake, Alaska",
"time": 1545672051177,
"updated": 1545672768461,
"tz": -540,
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ak20539699",
"detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/ak20539699.geojsonp",
"felt": null,
"cdi": null,
"mmi": null,
"alert": null,
"status": "automatic",
"tsunami": 0,
"sig": 104,
"net": "ak",
"code": "20539699",
"ids": ",ak20539699,",
"sources": ",ak,",
"types": ",geoserve,origin,",
"nst": null,
"dmin": null,
"rms": 0.82,
"gap": null,
"magType": "ml",
"type": "earthquake",
"title": "M 2.6 - 14km WNW of Big Lake, Alaska"
},
"geometry": {
"type": "Point",
"coordinates": [
-150.2,
61.5832,
17.5
]
},
"id": "ak20539699"
}
]
}
Related question: Google Maps JS API v3 - Simple Multiple Marker Example
Your "click" event listener needs to be inside the loop so it can be associated with each marker, and the content needs to be associated with the marker (the option used for that in the related question is function closure):
infowindow = new google.maps.InfoWindow();
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var text = '' + results.features[i].properties.place + '';
var latLng = new google.maps.LatLng(coords[1], coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
marker.addListener('click', (function(marker, text) {
return function(e) {
infowindow.setContent(text);
infowindow.open(map, marker);
}
})(marker, text));
}
proof of concept fiddle
code snippet:
var map, infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(2.8, -187.3),
mapTypeId: 'terrain'
});
infowindow = new google.maps.InfoWindow();
// Create a <script> tag and set the USGS URL as the source.
var script = document.createElement('script');
// This example uses a local copy of the GeoJSON stored at
// http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
script.src = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp';
document.getElementsByTagName('head')[0].appendChild(script);
}
// Loop through the results array and place a marker for each
// set of coordinates.
window.eqfeed_callback = function(results) {
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var text = '' + results.features[i].properties.place + '';
var latLng = new google.maps.LatLng(coords[1], coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
marker.addListener('click', (function(marker, text) {
return function(e) {
infowindow.setContent(text);
infowindow.open(map, marker);
}
})(marker, text));
}
}
#map {
height: 100%;
}
html,
body {
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>
When I click on one marker then at the same time I want other marker will be deleted from goggle map. Just like I do with infowindow, when I click on one marker then only its infowindow will open.
var locations = [
[
"Location 1",
"215 West Girard Avenue 19123",
"39.9695601",
"-75.1395161"
],
[
"Location 2",
"5360 Old York Road 19141",
"40.034038",
"-75.145223"
],
[
"Location 3",
"1350 W Girard Avenue 19123",
"39.9713524",
"-75.1590360"
]
];
gmarkers = [];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(39.9995601, -75.1395161),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
function createMarker(latlng, html) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
return marker;
}
for (var i = 0; i < locations.length; i++) {
alert(locations[i][0]);
gmarkers[locations[i][0]] =
createMarker(new google.maps.LatLng(locations[i][2], locations[i][3]), locations[i][0] + "<br>" + locations[i][1]);
}
You can put this code inside your for loop!
for (var i = 0; i < locations.length; i++) {
markerd[i] = new google.maps.Marker({
position: mark_1,
map: map,
zIndex: i
});
google.maps.event.addListener(markerd[i], 'click', function() {
for (i = 0; i < markerd.length; i++) {
if (this.index != i){
markerd[i].setMap(null);
markerp[i].setMap(null);
line[i].setMap(null);
}
}
});
}
I have created a Google Maps Multiple locations page,
using Advanced Custom Fields Google Map field.
I have managed to make the marker icon change when clicked on, but I want it to be changed back when clicking on other icons.
here is an example of the code:
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,
icon: iconBase + 'Stock%20Index%20Up.png'
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0], locations[i][6]);
infowindow.open(map, marker);
marker.setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Down.png");
}
})(marker, i));
Better look of the working code here:
http://jsfiddle.net/gargiguy/s8vgxp3g
What duncan said: What you want to do is add all your markers to an array. In your click event handler, loop over that array, updating each marker's icon. Then finally set the icon for just the marker that's been clicked.
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0], locations[i][6]);
infowindow.open(map, marker);
for (var j = 0; j < markers.length; j++) {
markers[j].setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Up.png");
}
marker.setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Down.png");
};
working fiddle
working code snippet:
var markers = [];
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
// center: new google.maps.LatLng(-33.92, 151.25),
center: new google.maps.LatLng(36.8857, -76.2599),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var iconBase = 'https://cdn3.iconfinder.com/data/icons/musthave/24/';
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,
icon: iconBase + 'Stock%20Index%20Up.png'
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0], locations[i][6]);
infowindow.open(map, marker);
for (var j = 0; j < markers.length; j++) {
markers[j].setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Up.png");
}
marker.setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Down.png");
};
})(marker, i));
markers.push(marker);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
var locations = [
[
"New Mermaid",
36.9079, -76.199,
1,
"Georgia Mason",
"",
"Norfolk Botanical Gardens, 6700 Azalea Garden Rd.",
"coming soon"
],
[
"1950 Fish Dish",
36.87224, -76.29518,
2,
"Terry Cox-Joseph",
"Rowena's",
"758 W. 22nd Street in front of Rowena's",
"found"
],
[
"A Rising Community",
36.95298, -76.25158,
3,
"Steven F. Morris",
"Judy Boone Realty",
"Norfolk City Library - Pretlow Branch, 9640 Granby St.",
"found"
],
[
"A School Of Fish",
36.88909, -76.26055,
4,
"Steven F. Morris",
"Sandfiddler Pawn Shop",
"5429 Tidewater Dr.",
"found"
],
[
"Aubrica the Mermaid (nee: Aubry Alexis)",
36.8618, -76.203,
5,
"Myke Irving/ Georgia Mason",
"USAVE Auto Rental",
"Virginia Auto Rental on Virginia Beach Blvd",
"found"
]
];
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div>
<div id="map" style="width: 500px; height: 400px;"></div>
</div>
Since it sounds like you only need to change the previous icon back to the original, I wouldn't recommend looping through every marker. In a map with a lot of markers, this could become quite heavy.
Instead, I would store the active marker in a variable on the click event, and just update that one when it changes.
var marker;
var activeMarker;
var iconDefault = iconBase + 'Stock%20Index%20Up.png';
var iconSelected = 'https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Down.png';
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,
icon: iconDefault
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0], locations[i][6]);
infowindow.open(map, marker);
// check to see if activeMarker is set
// if so, set the icon back to the default
activeMarker && activeMarker.setIcon(iconDefault);
// set the icon for the clicked marker
marker.setIcon(iconSelected);
// update the value of activeMarker
activeMarker = marker;
}
})(marker, i));
}
You can do same like below:
var prevMarker = "";
var markers = [];
var image = { url: "your_png.png",
scaledSize: new google.maps.Size(38, 40) // If you want to resize it.
};
For creating marker,
var marker = createMarker(coordinate, map, image, id);
// coordinate = {lat:float value,long:float value} and 'map' your map
function createMarker(lat, long, map, image, marker_id) {
var coordinates = {lat: lat, lng: long};
var marker = new google.maps.Marker({
position: coordinates,
icon: image,
id: "marker_" + marker_id,
map: map
});
return marker;
}
For marker action you can use.
marker.addListener('click', function() {
console.log(this.id);
if(prevMarker !== "") {
prevMarker.setIcon({
url: "your_image.png",
scaledSize: new google.maps.Size(38, 40)
});
}
prevMarker = this;
this.setIcon({
url: "your_image.png",
scaledSize: new google.maps.Size(48, 50)
});
map.panTo(this.getPosition());
});
loop marker code for all markers available.
I am trying to update the location of a marker with out refreshing the whole page. I have tried to use setTimeout(function() however I am having no luck..
here is my code I have so far..
thanks in advance
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(35.66, -80.50),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "getjson.php",
'dataType': "json",
'success': function (data) {
json = data; } });
return json;})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
here is my JSON output.
[{"lat":35.6606376,"lng":-80.5048653,"content":"bca"}, {"lat":42.6799504,"lng":-36.4949205,"content":"abc"}]
I would suggest using setInterval rather than setTimeout.
Here is some code that simulates an update via JSON in a fiddle, using your provided JSON with the required "description" member added for each marker:
var map = null;
var gmarkers = [];
var intervalNumber = 0;
setInterval(function () {
new Request.JSON({
url: '/echo/json/',
data: {
json: JSON.encode([{
"lat": 35.6606376 + (0.01 * intervalNumber),
"lng": -80.5048653 + (0.1 * intervalNumber),
"content": "bca",
"description":"first marker"
}, {
"lat": 42.6799504 + (0.01 * intervalNumber),
"lng": -36.4949205 - (0.1 * intervalNumber),
"content": "abc",
"description": "second marker"
}]),
delay: 3
},
onSuccess: function (response) {
update_map(response);
intervalNumber++;
}
}).send();
}, 5000);
update_map = function (data) {
var bounds = new google.maps.LatLngBounds();
// delete all existing markers first
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
gmarkers = [];
// add new markers from the JSON data
for (var i = 0, length = data.length; i < length; i++) {
latLng = new google.maps.LatLng(data[i].lat, data[i].lng);
bounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data[i].title
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description+"<br>"+marker.getPosition().toUrlValue(6));
infoWindow.open(map, marker);
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description+"<br>"+marker.getPosition().toUrlValue(6));
infoWindow.open(map, marker);
});
})(marker, data[i]);
gmarkers.push(marker);
}
// zoom the map to show all the markers, may not be desirable.
map.fitBounds(bounds);
};
function initialize() {
// initialize the map on page load.
var mapOptions = {
center: new google.maps.LatLng(35.66, -80.50),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
// add the markers to the map if they have been loaded already.
if (gmarkers.length > 0) {
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(map);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
https://developers.google.com/maps/documentation/javascript/reference
markerObject.setPosition(latlng:LatLng|LatLngLiteral)
I don't think you need to redraw the map, but in case you do:
google.maps.event.trigger(mapObject, 'resize');