1

我正在使用 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 ...
        }
    }
}

从结果中获取状态的最简单的代码是什么?根据地址组件类型的文档,我假设我会寻找“ short_name”中的“ administrative_area_level_1”。它是否正确?有没有比遍历结果更简单的方法来访问它,直到我找到“ administrative_area_level_1”?(我在页面上包含了 jquery,因此如果它使任何事情变得更简单,可以使用它进行编码)

4

1 回答 1

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>
于 2013-06-17T13:07:01.543 回答