2
votes

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>
1
Try logging the stringified location and see how it differs from when you define it outright. (also, why parseFloat(Number(?) - CertainPerformance
It does not differ at all. The log displays exactly what I want. Thats the funny part. - vdrog
I tried parseFloat , Number and parseFloat(Number(?)) , all 3 dont work - vdrog
Your backend seems to be broken - the JSON is not properly formatted, so parsing it will throw an error. - CertainPerformance
Sorry, the response I added above was missing a "}" parenthesis, added that in the question. The JSON shows as valid, I checked using jsonlint.com - vdrog

1 Answers

1
votes

You're accessing locations[i][1] as if locations[i] is an array, but you're pushing individual primitives to locations currently. Try pushing arrays to locations instead:

locations.push([f.restaurant_name, f.address.latitude, f.address.longitude]);

Also, rather than messing with IIFEs to deal with var's function scope problems, you would probably find it far easier to write code using let, which has block scope and is a lot easier to deal with. Or, even better, use forEach to iterate directly.

The other problem is that you need to make sure the map gets populated after the call to localhost, not before. As is, your code that creates the map runs immediately after the request is made, without waiting for the response. Instead, create the map only after the response comes back:

fetch('http://localhost:63342/295%20Project/api/response.json?')
  .then((data) => data.json())
  .then((data) => {
  const locations = data.map(({ restaurant_name, address: { latitude, longitude }}) => (
    [restaurant_name, latitude, longitude]
  ));
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 10,
    center: new google.maps.LatLng(37.328255, -121.883693),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  const infowindow = new google.maps.InfoWindow();
  locations.forEach(([name, lat, lng]) => {
    const marker = new google.maps.Marker({
      position: new google.maps.LatLng(lat, lng),
      map: map
    });
    google.maps.event.addListener(marker, "click", () => {
      infowindow.setContent(name);
      infowindow.open(map, marker);
    });
  });
});