我正在使用Google Maps JavaScript API v3。我有一张地图,每个州都有标记。当我单击状态标记时,我需要访问回调函数中的状态缩写。谷歌地图有原生的方式,我可以访问标记的状态吗?
google.maps.event.addListener(mark,'click',function(event){
// how can I access the state abbreviation (e.g. 'MO') from in here?
}
我知道我可以通过反向地理编码实现这一目标,但是有更简单(并且不易出错)的方式吗?
如果只能使用反向地理编码来完成,那么访问该状态的最简单代码是什么?我假设我的代码看起来像这样:
google.maps.event.addListener(mark,'click',function(event){
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
... get state from results ...
}
}
}
从结果中获取状态的最简单代码是什么?根据{{3}}的文档,我假设我会查找“short_name
”的“administrative_area_level_1
”。它是否正确?是否有更简单的方法来访问它而不是循环结果,直到找到“administrative_area_level_1
”? (我在页面上包含了jquery,因此可以使用它进行编码,如果它使任何更简单的事情)
答案 0 :(得分:1)
这是一个有效的例子:
<!DOCTYPE html>
<html>
<head>
<title>http://stackoverflow.com/questions/17144375/how-to-get-the-state-of-a-marker?noredirect=1#comment24816710_17144375</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100%; width:100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var markers = [
{lat:54.60039, lng:-3.13632, state:"AA"},
{lat:54.36897, lng:-3.07561, state:"ZZ"},
];
function initialize() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(54.42838,-2.9623),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var marker;
var infowindow = new google.maps.InfoWindow({
content: ''
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
for (var i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].lat,markers[i].lng),
map: map,
title:"marker " + i,
state: markers[i].state // a custom property of our own
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.state);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>