I am getting latitude and longitude as strings from a JSON response. I am parsing the response, extracting them and then storing them in an array. I am then using the array to populate markers on map using Google Maps.
My issue is, when I hard code the values in the locations array e.g:
var locations = [["Happy Restaurant", 37.328255, -121.883693]];
The marker is populated successfully. But when I use locations.push([f.restaurant_name, parseFloat(Number(f.address.latitude)), parseFloat(Number(f.address.longitude))]); The markers are not populated on map.
Hard coded values work perfectly but somehow, it is not able to populate the map using my array populated from JSON parsed response which has the same data. I tried using parseFloat and Number methods. Also tried toString. Nothing seems to work. What am I missing here?
my code:
map.js:
var locations = [];
$.getJSON("http://localhost:63342/295%20Project/api/response.json?",
function(data) {
$.each(data, function(i, f) {
//Log prints accurate data
console.log(f.restaurant_name + " " + parseFloat(Number(f.address.latitude)) + " " + parseFloat(Number(f.address.longitude)));
// tried using Number() parseFloat() and parseFloat(Number()) without success
locations.push(f.restaurant_name, parseFloat(Number(f.address.latitude)), parseFloat(Number(f.address.longitude)));
});
});
//create the map
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 10,
center: new google.maps.LatLng(37.328255, -121.883693),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker;
var i;
//populate the markers on map (works with hardocded values in the locations array)
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) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
//redirect markers to restaurant_detail.html
}
})(marker, i));
}
response.json:
[{
"restaurant_name": "Happy Eating",
"address": {
"longitude": -121.883693,
"city": "San Jose",
"zip": "95112",
"latitude": 37.328255,
"state": "CA",
"street_address": "545 S Second St"}
}]
html:
<div id="map" style="width: 100%; height: 400px;"></div>
logging the stringifiedlocationand see how it differs from when you define it outright. (also, whyparseFloat(Number(?) - CertainPerformanceparseFloat,NumberandparseFloat(Number(?)), all 3 dont work - vdrog