谷歌地图API - 对国家进行地理编码,然后在单击时缩放到国家边界

Google Maps API - Geocode countries then zoom to bounds of country on click

本文关键字:国家 单击 然后 缩放 边界 API 谷歌地图 编码      更新时间:2023-09-26

我有以下代码,它使用地理编码API在谷歌地图上放置国家标记。

这很好,但是我现在想在单击标记时放大该国家的边界,但我完全卡住了!

有什么想法吗?

Javascript:

var country = [];
var bounds;
var geocoder;
var marker;
$(document).ready(function () {
    $("select[id*='countryList']").find("option").each(function () {
        country.push([$(this).val(), $(this).text()]);
    });
    initialize();
});
function getCountry(country, countryTotal, theMap) {
    geocoder.geocode( { 'address': country }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
                map: theMap,
                title: ""+results[0].geometry.viewport,
                position: new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng())
            });
            marker.setIcon('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+countryTotal+'|B22222|FFFFFF') ;
            google.maps.event.addDomListener(marker, 'click', function () {
                // Zoom into the bounds of the country that has been clicked on...
            });
            bounds.extend(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
            theMap.fitBounds(bounds);
        } else if(status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            setTimeout(function() {
                getCountry(country, countryTotal, theMap)
            }, 10);
        }
    });
}
function initialize() {
    bounds = new google.maps.LatLngBounds();
    geocoder = new google.maps.Geocoder();
    var mapOptions = {
        scrollwheel: false,
    }
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    for (var i = 0; i < country.length; i++) {
        var countries = country[i];
        getCountry(countries[1], countries[0], map);
    }
}

.HTML:

<select name="countryList" id="countryList">
        <option value="1">Austria</option>
        <option value="1">Balearic Islands</option>
        <option value="2">Canary Islands</option>
        <option value="3">France</option>
        <option value="2">Italy</option>
        <option value="1">Madeira</option>
        <option value="1">Portugal</option>
        <option value="3">Spain</option>
        <option value="1">Turkey</option>
        <option value="18">UK</option>
</select>
<div id="map" style="width: 968px; height: 750px;"></div>

地理编码器结果还会返回包含边界的地址的几何。使用边界作为映射的fitBounds方法的参数:

google.maps.event.addDomListener(marker, 'click', function () {
   this.getMap().fitBounds(results[0].geometry.bounds)
});