Search code examples
google-mapsgoogle-maps-api-3

Google Maps API - Adding arbitrary data to Point in Data Layer


var schoolLayer = new google.maps.Data();
schoolLayer.setMap(map);
let latLng = new google.maps.LatLng(coords1, coords2);
let school = new google.maps.Data.Point(latLng);
schoolLayer.add({geometry: school});

I am building a school layer. I am doing this by adding points to a data layer. I added the points pretty easily. My question is, how do I add arbitrary data to the point, such as the school's name?

I tried to do schoolLayer.add({geometry: school, school_name: 'Hello Elementary School'}) but it does not work.


Solution

  • Put the arbitrary data in the properties field of the feature.

    let latLng = new google.maps.LatLng(37.4419, -122.1419);
    let school = new google.maps.Data.Point(latLng);
    schoolLayer.add({
      geometry: school,
      properties: {
        name: "school1"
      }
    });
    

    Then you can get it in an event listener like this:

    google.maps.event.addListener(schoolLayer, 'click', function(e) {
      infowindow.setContent(e.feature.getProperty("name"));
      infowindow.setOptions({
        pixelOffset: new google.maps.Size(0, -40)
      })
      infowindow.setPosition(e.latLng);
      infowindow.open(map);
    })
    

    proof of concept fiddle

    screenshot of resulting map

    function initialize() {
      var map = new google.maps.Map(
        document.getElementById("map_canvas"), {
          center: new google.maps.LatLng(37.4419, -122.1419),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      var infowindow = new google.maps.InfoWindow();
      var schoolLayer = new google.maps.Data();
      schoolLayer.setMap(map);
      let latLng = new google.maps.LatLng(37.4419, -122.1419);
      let school = new google.maps.Data.Point(latLng);
      schoolLayer.add({
        geometry: school,
        properties: {
          name: "school1"
        }
      });
      let latLng2 = new google.maps.LatLng(37.445, -122.145);
      let school2 = new google.maps.Data.Point(latLng2);
      schoolLayer.add({
        geometry: school2,
        properties: {
          name: "school2"
        }
      });
      google.maps.event.addListener(schoolLayer, 'click', function(e) {
        infowindow.setContent(e.feature.getProperty("name"));
        infowindow.setOptions({
          pixelOffset: new google.maps.Size(0, -40)
        })
        infowindow.setPosition(e.latLng);
        infowindow.open(map);
      })
    }
    google.maps.event.addDomListener(window, "load", initialize);
    html,
    body,
    #map_canvas {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="map_canvas"></div>