使用loadGeoJson加载标记数据

时间:2019-03-20 08:45:33

标签: javascript google-maps google-maps-markers

我正在从JSON文件(located here)中加载标记:

 map.data.loadGeoJson('https://api.myjson.com/bins/tz9ze'); 

我要实现的目标:

  1. 从json节点name加载properties并将其显示为标题。
  2. 从json节点icon加载properties,并将其显示为标记图标。

我该如何实现?

1 个答案:

答案 0 :(得分:0)

使用Style function(来自文档):

  

声明性样式规则
  如果要更新大量叠加层的样式(例如标记或折线),则通常必须遍历地图上的每个叠加层并分别设置其样式。使用数据层,您可以声明性地设置规则,这些规则将应用于整个数据集。当数据或规则更新时,样式将自动应用于每个功能。您可以使用功能属性自定义其样式。

赞:

map.data.setStyle(function(feature) {
  return {
    icon: feature.getProperty("icon"),
    title: feature.getProperty("name")
  }
});

proof of concept fiddle

screenshot of resulting map

JSON数据:

//JSON file content:
var geoJson = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [35.29182, 32.917633]
    },
    "properties": {
      "name": "Adrian",
      "icon": "http://maps.google.com/mapfiles/ms/micons/mechanic.png"
    }
  }, {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [35.0611, 33.2815]
    },
    "properties": {
      "name": "Chase",
      "icon": "http://maps.google.com/mapfiles/ms/micons/mechanic.png"
    }
  }, {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [34.8621, 33.0613]
    },
    "properties": {
      "name": "Lincoln",
      "icon": "http://maps.google.com/mapfiles/ms/micons/mechanic.png"
    }
  }, {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [35.1551, 33.2527]
    },
    "properties": {
      "name": "Jayden",
      "icon": "http://maps.google.com/mapfiles/ms/micons/mechanic.png"
    }
  }, {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [34.9047, 33.0816]
    },
    "properties": {
      "name": "Cameron",
      "icon": "http://maps.google.com/mapfiles/ms/micons/mechanic.png"
    }
  }]
};

代码段:

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {
      lat: 33.2815,
      lng: 35.0611
    }
  });

  // Load GeoJSON.
  map.data.loadGeoJson('https://api.myjson.com/bins/tz9ze');

  map.data.setStyle(function(feature) {
    return {
      icon: feature.getProperty("icon"),
      title: feature.getProperty("name")
    }
  });
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>