2

I have a map and a JSON file containing information on Restaurants. I need to add markers to the map for 20 of the restaurants from the JSON file, but I just can't get the map to load with the markers on. I don't think i'm retrieving the data from the JSON file correctly. A point in the right direction would be greatly appreciated.

Here is my code:

  var map;
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(55.9753905, -1.6236163),
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

       map = new 
         google.maps.Map(document.getElementById("EstablishmentCollection"),
           mapOptions);
           $.getJSON("'FHRS_json.json'", 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.BusinessName
               });
               marker.setMap(map);
               });
            });

And then this is sample of the start of the JSON file. There's loads of restaurants so I wont post it all.

 {
   "FHRSEstablishment": {
   "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
   "Header": {
   "ExtractDate": "2018-02-03",
   "ItemCount": "2369",
   "ReturnCode": "Success"
  },
"EstablishmentCollection": {
      "EstablishmentDetail": [
        {
          "FHRSID": "1011573",
          "LocalAuthorityBusinessID": "17/00395/MIXED",
          "BusinessName": "#Central",
          "BusinessType": "Pub/bar/nightclub",
          "BusinessTypeID": "7843",
          "AddressLine1": "15 Marlborough Crescent",
          "AddressLine2": "Newcastle upon Tyne",
          "PostCode": "NE1 4EE",
          "RatingValue": "AwaitingInspection",
          "RatingKey": "fhrs_awaitinginspection_en-GB",
          "RatingDate": { "-xsi:nil": "true" },
          "LocalAuthorityCode": "416",
          "LocalAuthorityName": "Newcastle Upon Tyne",
          "LocalAuthorityWebSite": "http://www.newcastle.gov.uk/",
          "LocalAuthorityEmailAddress": "[email protected]",
          "SchemeType": "FHRS",
          "NewRatingPending": "False",
          "Geocode": {
            "Longitude": "-1.62244200000000",
            "Latitude": "54.96785900000000"
          }
        },
2
  • Need to show what comes before "EstablishmentCollection" in the json in order to accurately point at the array in "EstablishmentDetail" which is what you need to access. Also the values you need are in Geocode.Latitude and Geocode.Longitude. There is no data.lat or data.lng Commented Apr 29, 2018 at 17:28
  • @charlietfl i've added the begininning of the JSON file on, and oh yes! I'll change that thank you Commented Apr 29, 2018 at 17:32

3 Answers 3

1

I think the main problem you're having is you need to parse the floats. Currently they are just strings. You can create a marker with the following function. Just pass the establishment as an object into the function and it will create the marker for you:

   function createMarker(obj) {
        const LatLng = new google.maps.LatLng(
            parseFloat(obj.geocode.Latitude),
            parseFloat(obj.gecode.Longitude)
        );    marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            title: obj.BusinessName
        });
    }
Sign up to request clarification or add additional context in comments.

5 Comments

oh isee! would I replace obj with EstablishmentDetail? Sorry for the basic questions, i'm not too skilled with this.
Yes you would pass in The EstablishmentDetail object
So you would essentially put it in a for each loop passing in EstablishmentDetail[i]
@charlietfl no I do not. I’m essentially doing the same in the markers options with map: map. After all that’s what setMap does ;)
My bad...missed that
1

Try changing the loop to:

$.each(json1.EstablishmentCollection.EstablishmentDetail, function(key, data) {

  var coords = data.Geocode;
  //look in browser console for errors and/or proper lat/lng object
  console.log(coords)


  var latLng = new google.maps.LatLng(+coords.Latitude, +coords.Longitude);
  // Creating a marker and putting it on the map
  var marker = new google.maps.Marker({
    position: latLng,
    title: data.BusinessName
  });
  marker.setMap(map);
});

13 Comments

i've replaced the loop with that^^^ but my map doesn't load at all :/
the error in console says : Uncaught Jb {message: "initialize is not a function", name: "InvalidValueError", stack: "Error↵ at new Jb (maps.googleapis.com/m…T0Up42whRQeyw7X6UG9EAY&callback=initialize:156:51"}
Did you declare function initialize() inside another function?
Make sure script tag with function initialize() is before the one that loads the maps library
yes....then only do the markers inside the if() when those properties actually exist. Otherwise do nothing
|
1

Change your loop processing to process over the array in the JSON data:

$.each(jsonData.EstablishmentCollection.EstablishmentDetail, function(key, data) {
  var latLng = new google.maps.LatLng(data.Geocode.Latitude, data.Geocode.Longitude);
  // Creating a marker and putting it on the map
  var marker = new google.maps.Marker({
    position: latLng,
    title: data.BusinessName
  });
  marker.setMap(googleMap);
});

proof of concept fiddle

code snippet:

html,
body,
#googleMap {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="googleMap"></div>
<script>
  function initialize() {

    var center = new google.maps.LatLng(54.9753905, -1.6236163);
    var mapCanvas = document.getElementById("googleMap");
    var mapOptions = {
      center: center,
      zoom: 12
    };
    var googleMap = new google.maps.Map(mapCanvas, mapOptions);
    $.each(jsonData.EstablishmentCollection.EstablishmentDetail, function(key, data) {
      var latLng = new google.maps.LatLng(data.Geocode.Latitude, data.Geocode.Longitude);
      // Creating a marker and putting it on the map
      var marker = new google.maps.Marker({
        position: latLng,
        title: data.BusinessName
      });
      marker.setMap(googleMap);
    });
  }
</script>
<script>
  var jsonData = {
    "EstablishmentCollection": {
      "EstablishmentDetail": [{
        "FHRSID": "1011573",
        "LocalAuthorityBusinessID": "17/00395/MIXED",
        "BusinessName": "#Central",
        "BusinessType": "Pub/bar/nightclub",
        "BusinessTypeID": "7843",
        "AddressLine1": "15 Marlborough Crescent",
        "AddressLine2": "Newcastle upon Tyne",
        "PostCode": "NE1 4EE",
        "RatingValue": "AwaitingInspection",
        "RatingKey": "fhrs_awaitinginspection_en-GB",
        "RatingDate": {
          "-xsi:nil": "true"
        },
        "LocalAuthorityCode": "416",
        "LocalAuthorityName": "Newcastle Upon Tyne",
        "LocalAuthorityWebSite": "http://www.newcastle.gov.uk/",
        "LocalAuthorityEmailAddress": "[email protected]",
        "SchemeType": "FHRS",
        "NewRatingPending": "False",
        "Geocode": {
          "Longitude": "-1.62244200000000",
          "Latitude": "54.96785900000000"
        }
      }]
    }
  }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initialize"></script>

3 Comments

thankyou, however if i put the jsondata in a script the map still doesn't load, however there are no errors in the console. Yet if I try link it to the json file, the map still doesn't load but I get the "initialize is not a function" error again. I'm so confused because running your code snippet on here works, yet not when I write it on mine
You did include the load of the JSON data ($.getJSON("'FHRS_json.json'", function(json1) {, I removed that in the example).
yeah iadded it on the line above ($.each (jsondata......) and change the json1 to jsonData. is that right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.