我正在从JSON文件(located here)加载标记:
map.data.loadGeoJson('https://api.myjson.com/bins/tz9ze');
我想要实现的目标:
name
加载properties
并将其显示为标题。icon
加载properties
并将其显示为标记图标。我怎样才能实现这一目标?
使用Style function(来自文档):
声明式样式规则 如果要更新大量叠加层的样式(例如标记或折线),通常必须遍历地图上的每个叠加层并单独设置其样式。使用数据层,您可以以声明方式设置规则,并将它们应用于整个数据集。更新数据或规则时,样式将自动应用于每个功能。您可以使用功能属性来自定义其样式。
像这样:
map.data.setStyle(function(feature) {
return {
icon: feature.getProperty("icon"),
title: feature.getProperty("name")
}
});
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>