我在浏览google maps api标签方面遇到了一些麻烦。我正在调用我的geojson并加载我的地图:
var map;
function init() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 43.2, lng: -84.65},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.data.loadGeoJson(
'Maps/Newark.geojson');
map.data.setStyle({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 4,
fillColor: 'blue',
fillOpacity: .5,
strokeColor: 'blue',
strokeWeight: 1
}
})
}
这是geojson数据样本:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ -84.69729,43.24808 ]
},
"properties": {
"Name":"Name 1",
"Address":"My Address",
"City":"town",
"State":"ST",
"Zip":12345,
"Group":"Newark"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ -84.58872,43.23395 ]
},
"properties": {
"Name":"Name 2",
"Address":"another address",
"City":"town",
"State":"ST",
"Zip": 12345,
"Group":"Newark"
}
}
]
}
我想要做的是通过标记显示名称属性作为标签。
我尝试了this但无法使其正常工作。
答案 0 :(得分:0)
从Google Maps API draw a text from GeoJSON point geometry修改
的变化:
map.data.setMap(null);
(因为我假设您仍然希望显示标记代码段
function initialize() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(43.23395, -84.58872),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds();
map.data.addListener('addfeature', function(evt) {
if (evt.feature.getGeometry().getType() == "Point") {
var coord = evt.feature.getGeometry().get();
bounds.extend(coord);
map.fitBounds(bounds);
var labelText = evt.feature.getProperty("Name");
var labelDiv = document.createElement("div");
labelDiv.innerHTML = labelText;
labelDiv.setAttribute("id", "label");
var myOptions = {
content: labelDiv,
boxStyle: {
border: "none",
textAlign: "center",
width: "50px"
},
disableAutoPan: true,
pixelOffset: new google.maps.Size(-25, 0),
position: coord,
closeBoxURL: "",
isHidden: false,
pane: "mapPane",
enableEventPropagation: true
};
var ibLabel = new InfoBox(myOptions);
ibLabel.open(map);
}
});
map.data.addGeoJson(geoJson);
}
google.maps.event.addDomListener(window, "load", initialize);
var geoJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-84.69729, 43.24808]
},
"properties": {
"Name": "Name 1",
"Address": "My Address",
"City": "town",
"State": "ST",
"Zip": 12345,
"Group": "Newark"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-84.58872, 43.23395]
},
"properties": {
"Name": "Name 2",
"Address": "another address",
"City": "town",
"State": "ST",
"Zip": 12345,
"Group": "Newark"
}
}
]
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
background-color: white;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/infobox/src/infobox.js"></script>
<div id="map_canvas"></div>