google map api InfoWindows - javascript

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>

Related

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>

Google Maps JS API + JSON - Multiple markers not showing up

So, what I need is very simple, I need to put markers in a map, I get the data from a JSON I built using PHP. I looked up all other questions(really) about Google Maps markers not showing up, and none of them worked for me. I can't find the flaw in my code.
The JSON is like this (but 58 items long), 'id' is unimportant:
[
{
"id": "2",
"lat": "-49.217290",
"lon": "-16.416160",
"tit": "Heinz",
"desc": "18 Machines"
},
{
"id": "3",
"lat": "-49.235455",
"lon": "-16.676926",
"tit": "Warehouse",
"desc": "10 Machines"
}
]
I'm new here, sorry if I do something wrong. My code is bellow:
<div id="map" class="height-400"></div>
<script>
var map;
var myLatLon = {lat: -16.398293, lng: -48.965098};
var markers = [];
$.ajax({
dataType:'json',
url: "contents/map_data.php",
success: function(data){
markers = data;
}
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLon,
zoom: 4,
//disableDefaultUI: true,
});
var i= 0;
$.each(markers, function(i, item) {
if(typeof item == 'object') {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(item.lat),parseFloat(item.lon)),
map: map,
title: item.titulo,
label: item.desc
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(item.desc);
infowindow.open(map, marker);
}
})(marker, i));
i=i+1;
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_SECRET_KEY&callback=initMap" async defer></script>
Markers variable is an empty array, cause the AJAX request has not returned yet. You should either move your code inside success callback or invoke it from success callback.
Try something like:
<div id="map" class="height-400"></div>
<script>
var map;
var myLatLon = {lat: -16.398293, lng: -48.965098};
var markers = [];
$.ajax({
dataType:'json',
url: "contents/map_data.php",
success: function(data){
markers = data;
initMap();
}
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLon,
zoom: 4,
//disableDefaultUI: true,
});
var i= 0;
$.each(markers, function(i, item) {
if(typeof item == 'object') {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(item.lat),parseFloat(item.lon)),
map: map,
title: item.titulo,
label: item.desc
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(item.desc);
infowindow.open(map, marker);
}
})(marker, i));
i=i+1;
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_SECRET_KEY&callback=initMap" async defer></script>

Google Heat Maps displaying red blocks

Some data is producing Google Heat Maps to display red blocks instead of the Heat Layer. I checked my information but I couldn't find anything wrong, here is my code:
for (i = 0; i < markers.length; i++) {
if (markers[i].lat != " ") {
mar.push(markers[i]);
var weightedLoc = {
location: new google.maps.LatLng(mar[j].lat,mar[j].lon),
weight: mar[j].Intensity
};
heat.push(weightedLoc);
j++;
}
}
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(mar[0].lat, mar[0].lon)
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
var pointArray = new google.maps.MVCArray(heat);
heatmap = new google.maps.visualization.HeatmapLayer({
data: heat
});
heatmap.setMap(map);
My data is in this json format:
[
{"lat":"-0.05487","lon":"-78.45286","Intensity":"1.86"},
{"lat":"-0.09377","lon":"-78.45136","Intensity":"2"},
{"lat":"-0.05489","lon":"-78.45283","Intensity":"0.6"}
]
Thanks!
weight has to be of type number, currently it's a string.
Convert it via :
weight: parseFloat(mar[j].Intensity)
proof of concept fiddle
code snippet:
function initialize() {
var markers = [{
"lat": "-0.05487",
"lon": "-78.45286",
"Intensity": "1.86"
}, {
"lat": "-0.09377",
"lon": "-78.45136",
"Intensity": "2"
}, {
"lat": "-0.05489",
"lon": "-78.45283",
"Intensity": "0.6"
}];
var heat = [];
for (i = 0; i < markers.length; i++) {
if (markers[i].lat != " ") {
// mar.push(markers[i]);
var weightedLoc = {
location: new google.maps.LatLng(markers[i].lat, markers[i].lon),
weight: parseFloat(markers[i].Intensity)
};
heat.push(weightedLoc);
// j++;
}
}
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(markers[0].lat, markers[0].lon)
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
var pointArray = new google.maps.MVCArray(heat);
heatmap = new google.maps.visualization.HeatmapLayer({
data: heat
});
heatmap.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#dvMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=visualization"></script>
<div id="dvMap"></div>
When I experienced this problem, it was because I was accidentally passing empty strings values into the LatLng constructors.
See below:
for (i = 0; i < coords.length; i++) {
var lat = coords[i]
var long = coords[++i]
points.push(new google.maps.LatLng(lat, long)); //<-- no checks on lat, long
}
// heatmap layer
heatmap = new google.maps.visualization.HeatmapLayer({
data: points,
map: map
});
I discovered that there was a potential for lat or long to be empty, so I made the following change:
if (!lat.isEmpty() && !long.isEmpty()) {
points.push(new google.maps.LatLng(lat, long));
}
If the accepted answer does not solve your problems, check to ensure that all of the points you are passing to the heat map are valid.

Not getting infoWindow on my map

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);
}
})());
}
}

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