使用Google Maps为来自geoJson文件的点创建自定义标记

23

我正在使用GeoJSON作为Google Maps的数据源。我正在使用API的v3来创建如下的数据层:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
function initialize() {

  //Initialise the map
  var myLatLng = new google.maps.LatLng(53.231472,-0.539783);
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 17,
    center: myLatLng,
    scrollwheel: false,
    panControl: false,
    zoomControl: false,
    scaleControl: true,
    disableDefaultUI: true
  });

  //Initialise base folder for icons
  var iconBase = '/static/images/icons/';

  //Load the JSON to show places
  map.data.loadGeoJson('/api/geo');

}

google.maps.event.addDomListener(window, 'load', initialize);
</script>

<div id="map-canvas"></div>

我的 GeoJSON 数据来源如下:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "icon": "/static/images/icons/map-marker-do.png",
        "coordinates": [
          -0.53743,
          53.23437
        ]
      },
      "properties": {
        "name": "Cathedral",
        "description": "One of Europe’s finest Gothic buildings, once the tallest building in the world that dominates Lincoln's skyline.",
        "icon": "/static/images/icons/map-marker-do.png"
      }
    }
  ]
}

我想要做的是让地图上的标记图标来自于JSON中的"icon"属性,但是我无法弄清楚如何获取数据来更改默认标记。有人可以提供任何建议吗?谢谢。


你在哪里添加标记?你对 iconBase 做什么? - MrUpsidown
@MrUpsidown:他使用一个数据层,通过loadGeoJson加载的功能(例如标记/点)将由API自动添加。 - Dr.Molle
我的错。我看到JSON中的iconBase与URL的一部分,没有深入思考 :-) - MrUpsidown
1个回答

41

使用样式函数(样式函数使您能够基于特定功能应用样式)

  map.data.setStyle(function(feature) {
    return {icon:feature.getProperty('icon')};
  });

太好了。非常感谢。 :) - doubleplusgood

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接