Incorporating multiple markers into Google Maps with the help of a JSON file

I am struggling to display markers on a map for 20 restaurants from a JSON file. It seems like I may not be retrieving the data correctly. Any help or guidance in the right direction would be greatly appreciated.

My current code is as follows:

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

Here is a snippet of the beginning of the JSON file which contains information about various restaurants.

{
   "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": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12626160527c7765717361667e773c75797b">[email protected]</a>",
          "SchemeType": "FHRS",
          "NewRatingPending": "False",
          "Geocode": {
            "Longitude": "-1.62244200000000",
            "Latitude": "54.96785900000000"
          }
        },

Answer №1

It appears that the main issue you are encountering is the need to convert the floats from strings. By implementing the following function, you can create a marker easily by passing the establishment as an object:

   function generateMarker(entity) {
        const coordinates = new google.maps.LatLng(
            parseFloat(entity.geocode.Latitude),
            parseFloat(entity.gecode.Longitude)
        );    
        
        marker = new google.maps.Marker({
            position: coordinates,
            map: map,
            title: entity.BusinessName
        });
    }

Answer №2

Consider updating the loop to this:

$.each(json1.EstablishmentCollection.EstablishmentDetail, function(index, item) {

  var location = item.Geocode;
  //check browser console for any errors and ensure correct lat/lng object
  console.log(location)


  var coordinates = new google.maps.LatLng(+location.Latitude, +location.Longitude);
  // Creating a marker and adding it to the map
  var newMarker = new google.maps.Marker({
    position: coordinates,
    title: item.BusinessName
  });
  newMarker.setMap(map);
});

Answer №3

Revamp your loop processing to iterate through the array within 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 placing it on the map
  var marker = new google.maps.Marker({
    position: latLng,
    title: data.BusinessName
  });
  marker.setMap(googleMap);
});

view demonstration fiddle

snippet of code:

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 placing 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": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9b9babb89a7acbeaaa8babda5ace7aea6bfe7bca2">[email protected]</a>",
        "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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you add draggable functionality to a Bootstrap dropdown menu?

My custom bootstrap dropdown design <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span cla ...

PHP not displaying line breaks from JavaScript textarea

I am facing an issue while trying to generate a .txt file on my server upon form submission. Despite including newlines in the comment section, they do not show up in the resulting .txt file. Below is the code snippet I am using: Javascript function sen ...

Switching from PHP to JavaScript before returning to PHP to establish and manage sessions

Currently, I am in the process of resolving an issue I am facing. The problem arises when utilizing the following code for someone trying to sign into the admin panel: <script> function myFunction() { //alert('you can type now, end ...

Guide to specifying optional JSON fields in Golang structures?

In my programming practice, I have a preference for using pointers with primitive data types in my structs. By doing so, I ensure that when I use json.Marshal to convert them, any nil fields are represented as "field": null in the resulting JSON string. Ho ...

"Exploring the Power of Angular Change Detection with Promises in a Hybrid

We are currently in the process of upgrading an AngularJS project to Angular 7 by following the recommended "hybrid" approach where both frameworks coexist. However, we have encountered some issues with change detection when dealing with native promises. T ...

Updating the state of an array containing objects within an array of objects in React

I have a state called invoices, which is an array of objects structured like this: const [invoices, setInvoices] = useState([ { id: 123, tag_number: "", item_amounts: [ { item: "processing", amount: 159 }, { i ...

What is the best method for integrating JavaScript into my Express.js application that is also utilizing Socket.IO?

In order to synchronize time for my countdown project, I am utilizing the timesync package. server.js const app = require('express')(); const http = require('http').Server(app); const io = require('socket.io')(http); const po ...

I currently have a set of 6 popovers that all open simultaneously, but I am looking to make them open sequentially, one after

My component generates a div with 6 different experiences, each with its own popover. However, when I click on an experience to open its popover, all 6 popovers appear. How can I assign a unique ID to each popover? This is the code for my experience compo ...

What is the most efficient method for transforming an index into a column number that resembles that of Excel using a functional approach?

Is there a way to write a function that can produce the correct column name for a given number, like A for 1 or AA for 127? I know this question has been addressed numerous times before, however, I am interested in approaching it from a functional perspect ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

Terminate the rethinkdb data stream

Currently delving into the world of RethinkDB and am eager to utilize the changes() method to fetch a changefeed. While I've figured out how to initiate them, the documentation doesn't quite explain how to halt a changefeed. Is it sufficient to ...

A guide to accessing a specific worksheet on a Sharepoint Excel spreadsheet using Python

In my Python project, I am using the Office 365 REST Python Client library to access and read an excel workbook with multiple sheets. Although I have successfully authenticated, I am struggling to correctly append the sheet name to the file name in order ...

Customize the CSS for the column containers in Material-UI's DataGrid with the

I am facing a challenge in trying to override the CSS property position on the .MuiDataGrid-columnsContainer. Upon reviewing the information available on https://material-ui.com/api/data-grid/#css, it seems that there is a rule defined for root but not spe ...

Customizing an image with personalized text and then sending it to a server using a combination of javascript and

Looking for a way to add text to an image saved on the server, then save the edited image back to the server. I've heard using canvas is the best approach, but struggling to find the specific solution I need. ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

Calculating the height of the browser menubar, toolbar, navigation bar, and bookmarks can be easily achieved using jQuery or JavaScript

How can I use jQuery to calculate the height of the browser and adjust the position of another div element accordingly? What steps do I need to take to achieve this functionality? ...

I could use some help understanding how to identify the parent file so I can elevate a state

I'm facing a challenge in lifting up a state so that I can utilize it across various pages. The confusion lies in determining where to reference the states, given the uncertainty regarding the parent location. Since this is my first attempt at designi ...

Position a div element after another using the :after pseudo-element

My goal is simple to explain, but I have exhausted all my efforts trying to achieve it. I am hoping for the ★ symbol to appear immediately after the number 06 using jQuery. Any assistance would be greatly appreciated. The numbers are generated by a s ...

A program that saves numerous data from a JSON dictionary into an array

I have a large collection of dictionaries in JSON format obtained through an API request totaling over 1000. How can I develop a script that can loop through all the dictionaries and extract the values from one specific key-value pair? For instance: "te ...

DailyCodingChallenge: Discover two elements in an array that add up to a specified value

As someone who is relatively new to coding, I recently signed up for the daily coding problem mailing list and received the following question: If given a list of numbers and a specific number k, can you determine whether any two numbers from the list a ...