Search code examples
jqueryjsongoogle-mapsget

Displaying JSON File in Google Map Window


I am trying to display a json file in a Google Map window.

Chrome's privacy policy makes it extremely complicated to display a local json file from within your own domain.

I have attempted to run a local webserver, serve up the file and make the AJAX call to localhost, using the $.getJSON method to display the information, internally.

   <!DOCTYPE html>
    <html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <title>Info windows</title>
        <style type="text/css">/* 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>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
    <div id="map"></div>
    <script>

          // This example displays a marker at the center of Australia.
          // When the user clicks the marker, an info window opens.

          function initMap() {
            var hc = {lat: 40.4512, lng: -85.3700};
            var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 4,
              center: hc
            });

    var obj = $.getJSON( "ajax/GeoObs.json", function( data ) {
      var items = [];
      $.each( data, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val + "</li>" );
      });

      $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
      }).appendTo( "body" );
    });

            var infowindow = new google.maps.InfoWindow({
              content: obj
            });

            var marker = new google.maps.Marker({
              position: hc,
              map: map,
              title: 'Hartford City'
            });
            marker.addListener('click', function() {
              infowindow.open(map, marker);
            });
          }
        </script><script async defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCz672JUYjod6zzfxnBg_rzBNsBfbbjpJc&callback=initMap">
        </script></body>
    </html>

This displays the marker and creates a window. However, it does not display any data.


Solution

  • As fellow coders have already suggested, getJSON is asynchronous so you must take that into account before the infowindow can show its content. This is another approach you can take:

    function initMap() {
     var hc = {lat: 40.4512, lng: -85.3700};
     var map = new google.maps.Map(document.getElementById('map'), {
     zoom: 4,
     center: hc
     });
    
     var obj = $.getJSON( "ajax/GeoObs.json", function( data ) {
     var items = [];
        $.each( data, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val + "</li>" );
        });
    
     $( "<ul/>", {
     "class": "my-new-list",
      html: items.join( "" )
     }).appendTo( "body" );
    });
    
      var infowindow = new google.maps.InfoWindow({
        content: "Simple Test"
      });
    
      var marker = new google.maps.Marker({
        position: hc,
        map: map,
        title: 'Hartford City'
      });
    

    Then just add an event listener such as bounds_changed so that when the map loads up, the content inside the infowindow can get displayed:

      google.maps.event.addListener(map, "bounds_changed", function(){
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map, marker);
        });
      });
    }
    

    Here is a JSBIN to show how it works