How to create multiple infowindow in google map api - javascript

I create 3 markers in the map whose data comes from a json. but when I click on a marker and try to open the Info window only the last marker will response correctly.. please help me.... this the code....
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js" type="text/javascript"></script>
</head>
<body>
<script>
var json = [
{
"title": "Stockholm",
"lat": 59.3,
"lng": 18.1,
"description": "Stockholm is the capital and the largest city of Sweden and constitutes the most populated urban area in Scandinavia with a population of 2.1 million in the metropolitan area (2010)"
},
{
"title": "Oslo",
"lat": 59.9,
"lng": 10.8,
"description": "Oslo is a municipality, and the capital and most populous city of Norway with a metropolitan population of 1,442,318 (as of 2010)."
},
{
"title": "Copenhagen",
"lat": 55.7,
"lng": 12.6,
"description": "Copenhagen is the capital of Denmark and its most populous city, with a metropolitan population of 1,931,467 (as of 1 January 2012)."
}
]
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
for (var i = 0, length = json.length; i < length; i++) {
var data=json[i];
var latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
var infowindow = new google.maps.InfoWindow({
content: data.description
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="googleMap" style="width:100%;height:100%;"></div>
</body>
</html>

The problem is if you try and assign content to the infowindow within a loop. Then when you click the marker, it only knows about the content from the very last iteration of the loop. You need a closure instead. There's a couple of different ways to handle this, here's how I usually do it:
function initialize() {
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var infowindow = new google.maps.InfoWindow({
content: ""
});
for (var i = 0, length = json.length; i < length; i++) {
var data=json[i];
var latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
bindInfoWindow(marker, map, infowindow, data.description);
}
}
function bindInfoWindow(marker, map, infowindow, description) {
marker.addListener('click', function() {
infowindow.setContent(description);
infowindow.open(map, this);
});
}

Related

Pressing a button populate a google map with markers from an external json file

I have the above code and I want to have an external json file not an embedded as it is shown. Pressing a button(on the map at the top left side), all the markers have to be placed on the map.(These markers from the json file via ajax call).And pressing a second button the markers have to disappear. And all these without the use of jquery. Have you got any suggestions?
<!DOCTYPE html>
<html>
<head>
<title>My map</title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Aksa Beach',
"lat": '19.1759668',
"lng": '72.79504659999998',
"description": 'Aksa Beach is a popular beach and a vacation spot in Aksa village at Malad, Mumbai.'
},
{
"title": 'Juhu Beach',
"lat": '19.0883595',
"lng": '72.82652380000002',
"description": 'Juhu Beach is one of favourite tourist attractions situated in Mumbai.'
},
{
"title": 'Girgaum Beach',
"lat": '18.9542149',
"lng": '72.81203529999993',
"description": 'Girgaum Beach commonly known as just Chaupati is one of the most famous public beaches in Mumbai.'
},
{
"title": 'Jijamata Udyan',
"lat": '18.979006',
"lng": '72.83388300000001',
"description": 'Jijamata Udyan is situated near Byculla station is famous as Mumbai (Bombay) Zoo.'
},
{
"title": 'Sanjay Gandhi National Park',
"lat": '19.2147067',
"lng": '72.91062020000004',
"description": 'Sanjay Gandhi National Park is a large protected area in the northern part of Mumbai city.'
}
];
window.onload = function () {
LoadMap();
}
function LoadMap() {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + data.description + "</div>");
infoWindow.open(map, marker);
});
})(marker, data);
latlngbounds.extend(marker.position);
}
var bounds = new google.maps.LatLngBounds();
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
}
</script>
<div id="dvMap" style="width: 600px; height: 600px">
</div>

How do I add a listener to multiple markers which call the same function to display directions on click in google maps api v3

var x1 = 0;
var startPoint = new google.maps.LatLng(0, 0);
var endPoint = new google.maps.LatLng(0, 0);
var marker;
var latlngs = new Array();
var infowindow;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var locations = [
{
"name": "Frankie Johnnie & Luigo Too",
"address": "939 W El Camino Real, Mountain View, CA",
"lat": 37.386339,
"lng": -122.085823
}, {
"name": "Amici's East Coast Pizzeria",
"address": "790 Castro St, Mountain View, CA",
"lat": 37.38714,
"lng": -122.083235
}, {
"name": "Kapp's Pizza Bar & Grill",
"address": "191 Castro St, Mountain View, CA",
"lat": 37.393885,
"lng": -122.078916
}, {
"name": "Round Table Pizza: Mountain View",
"address": "570 N Shoreline Blvd, Mountain View, CA",
"lat": 37.402653,
"lng": -122.079354
}];
Edit: these are the global variables just to clarify ^
I want create a "click on markers to get directions" functionality. So far I have created a list in JSON that creates all the markers from the "lat" and "long" in the list without a problem:
for (var k in locations) {
latlngs[k] = new google.maps.LatLng(locations[k].lat, locations[k].lng);
marker = new google.maps.Marker({
position: latlngs[k],
animation: google.maps.Animation.DROP,
title: locations[k].name,
map: map
});
};
The JSON list ( locations[k] ) is 132 locations in total. I want to be able to click on a marker, save it as a start point for directions then wait for the secnond marker to be clicked on, which will be saved as an end point. Clicking the second marker will calculate and show directions as Iv'e tried below:
google.maps.event.addListener(marker, 'click', function () {
if (x1 === 0) {
startPoint = this.marker.position;
var infowindow = new google.maps.InfoWindow({
content: "Start",
position: startPoint
});
infowindow.open(map, this.marker);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
x1++;
} else {
endPoint = this.marker.position;
x1 = 0;
calculateDirections(startPoint, endPoint);
}
});
At this point no infowindow gets displayed and I get the error saying "cannot read 'position' of undefined". I can get the directions to show when I hardcode the start and end points.
The following threads touches on the same idea but don't answer the listener for all markers problem, which I think is the main issue.
Google Maps API V3 - add event listener to all markers?
and
how do I add same event listener to many markers and then differentiate between the markers in the listeners in google maps api v3?
If you get the LatLang on click then saving it wont be a big deal. I have tried to achieve this on click and get the latlang. I am not sure how much this will solve your problem but definitely will give you some idea to move ahead.
Here is the working example, and I hope this will help you.
var map;
var geocoder;
var mapOptions = { center: new google.maps.LatLng(37.09024, -95.712891),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initialize() {
var myOptions = {
center: new google.maps.LatLng(37.09024, -95.712891),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
var marker;
function placeMarker(location) {
if(marker){ //on vérifie si le marqueur existe
marker.setPosition(location); //on change sa position
}else{
marker = new google.maps.Marker({ //on créé le marqueur
position: location,
map: map
});
}
document.getElementById('lat').value=location.lat();
document.getElementById('lng').value=location.lng();
getAddress(location);
}
function getAddress(latLng) {
geocoder.geocode( {'latLng': latLng},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
document.getElementById("address").value = results[0].formatted_address;
}
else {
document.getElementById("address").value = "No results";
}
}
else {
document.getElementById("address").value = status;
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script><input type="text" id="address" size="30"><br><input type="text" id="lat" size="10"><input type="text" id="lng" size="10">
<div id="map_canvas"></div>

Marker not showing in google map for external JSON file

I have a crime_map.txt file to be shown on a map.
My HTML :
<div id="crime-map" style="width: 100%; height: 400px"></div>
And Javascript :
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&sensor=true">
</script>
<script type="text/javascript">
initialize();
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center : new google.maps.LatLng(26.152891, 91.781718)
};
map = new google.maps.Map(document.getElementById("crime-map"),mapOptions);
}
</script>
<script>
$(document).ready(function() {
$.getJSON("crime_points.txt", function(json1) {
$.each(json1, function(key, data) {
var latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
title: data.title
});
marker.setMap(map);
//console.log(marker);
});
});
});
</script>
And the crime_map.txt :
[{
"title": "Stockholm",
"lat": 26.17189,
"lng": 91.7645983333333,
"description": "Stockholm is the capital and the largest city of Sweden and constitutes the most populated urban area in Scandinavia with a population of 2.1 million in the metropolitan area (2010)"
},
{
"title": "Oslo",
"lat": 26.1717463,
"lng": 91.7645724,
"description": "Oslo is a municipality, and the capital and most populous city of Norway with a metropolitan population of 1,442,318 (as of 2010)."
},
{
"title": "Copenhagen",
"lat": 26.1444045,
"lng": 91.7860568,
"description": "Copenhagen is the capital of Denmark and its most populous city, with a metropolitan population of 1,931,467 (as of 1 January 2012)."
}]
But when I run the code, the map is shown but can't see any markers there ! Whats wrong going on ?
REF :StackOvrflow Link
EDITED TO :
<script type="text/javascript">
initialize();
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center : new google.maps.LatLng(26.152891, 91.781718)
};
map = new google.maps.Map(document.getElementById("crime-map"),mapOptions);
}
$(document).ready(function() {
console.log(map);
$.getJSON("crime_points.txt", function(json1) {
$.each(json1, function(key, data) {
var latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
title: data.title
});
marker.setMap(map);
//console.log(marker);
});
});
});
</script>
make it a single script , you can not declare a variable and get it from another script . based on your code structure , this is the most close solution i made for you . try it let me know if this works .
<script type="text/javascript">
initialize();
var map;
function initialize()
{
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center : new google.maps.LatLng(26.152891, 91.781718)
};
map = new google.maps.Map(document.getElementById("crime-map"),mapOptions);
$.getJSON("crime_points.txt", function(json1) {
$.each(json1, function(key, data) {
var latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
title: data.title
});
marker.setMap(map);
//console.log(marker);
});
});
}
</script>
here is the live code example using your json , have a look live demo

Multiple markers in google map?

I'm not able to add multiple marker on Google map, Can someone see the code below and suggest. my Google not showing the marker for locations[] array.
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var home = new google.maps.Marker({
position: initialLocation,
map: map,
icon: 'http://www.wicfy.com/images/newmarkers/home-marker.png'
});
var myCity = new google.maps.Circle({
center:initialLocation, map:map, radius:25000, strokeColor:"#0000FF", strokeOpacity:0.8, strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4,
editable:true
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
var locations = [
["New Mermaid",28.8909,76.5796,1,"Georgia Mason","","Norfolk Botanical Gardens, 6700 Azalea Garden Rd.","coming soon"],
["1950 Fish Dish",28.6800,76.9200,2,"Terry Cox-Joseph","Rowena's","758 W. 22nd Street in front of Rowena's", "found"],
];
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,
icon: 'http://www.wicfy.com/images/newmarkers/home-marker.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, i));
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Add the markers and initialize the map to a valid center before trying to center it using geolocation.
var map;
function initialize() {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = [
["New Mermaid",28.8909,76.5796,1,"Georgia Mason","","Norfolk Botanical Gardens, 6700 Azalea Garden Rd.","coming soon"],
["1950 Fish Dish",28.6800,76.9200,2,"Terry Cox-Joseph","Rowena's","758 W. 22nd Street in front of Rowena's", "found"],
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
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: 'http://www.wicfy.com/images/newmarkers/home-marker.png'
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0], locations[i][6]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
working example

Google map api v3 doesnt appear when plotting markers

I was following this tutorial: http://www.youtube.com/watch?v=7mkOVjRz3tg
but grabbing info from my DB instead and my map just appeared as a white screen with no map.
I had this running on an android app but then I had too many dots to plot that the android app stopped working so I am trying to make it a web interface. Any help would be appreciated. Also this is my first time dealing with js
a snippet of the json looks like:
{
"coords": [
{
"latitude": "33.702908",
"longitude": "-86.370771",
"id": ""
},
{
"latitude": 0,
"longitude": 0,
"id": "(null)"
},
{
"latitude": "0.000000",
"longitude": "0.000000",
"id": "00004561-CE13-4125-A244-989D2E984A91"
},
{
"latitude": "33.273388",
"longitude": "-86.832977",
"id": "0000F355-43B0-4164-9CD4-0D7C57A1B37C"
}
]
}
Html + js
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body, #map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="jquery-1.10.2.min.js"></script>
<script >
function getUserLocs(callback){
$.getJSON('http://www.url.com', callback)
}
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'H'
});
getUserLocs(function(data){
var locs = data.coords;
for (i in locs) {
var lat = locs[i];
var lon = locs[i];
latLng = new google.maps.LatLng(lat, lon);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: 'H'
});
}) LINE 51 this where the syntax error is
}
</script>
<script>
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
errors: SyntaxError: syntax error map.html:51
You miss one "}" after the creating marker.
getUserLocs(function(data){
var locs = data.coords;
for (i in locs) {
var lat = locs[i];
var lon = locs[i];
latLng = new google.maps.LatLng(lat, lon);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: 'H'
});
} // <-- here
});
To map the markers from JSON, you need to change your code:
getUserLocs(function(data){
var locs = data.coords;
for (i in locs) {
var lat = parseFloat(locs[i].latitude, 10);
var lon = parseFloat(locs[i].longitude, 10);
var latLng = new google.maps.LatLng(lat, lon);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: 'H'
});
}
});
http://googlemaps.googlermania.com/tmp/stackoverflow/21196413/test.html

Categories

Resources