Google Maps API - 将任意数据添加到数据层中的Point

时间:2018-05-18 17:16:14

标签: google-maps google-maps-api-3

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

我正在建立一个学校图层。我这样做是通过向数据层添加点。我很容易添加积分。我的问题是,如何添加任意数据,例如学校的名称?

我尝试schoolLayer.add({geometry: school, school_name: 'Hello Elementary School'}),但它不起作用。

1 个答案:

答案 0 :(得分:1)

将任意数据放在要素的属性字段中。

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

然后你可以在这样的事件监听器中得到它:

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"></script>
<div id="map_canvas"></div>
&#13;
&#13;
&#13;