javascript 将 Google 地图居中到位置字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28049383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:20:14  来源:igfitidea点击:

Center Google Maps to location string

javascriptgoogle-mapsgoogle-maps-api-3geolocation

提问by trs

Using Google Maps API, I would like to center the map to a string instead of Lat/Lng

使用 Google Maps API,我想将地图居中到一个字符串而不是 Lat/Lng

var mapOptions = {
    center: "Paris"
};

回答by MrUpsidown

You can use the geocoder:

您可以使用地理编码器

var geocoder;
var map;

function initialize() {

    geocoder = new google.maps.Geocoder();

    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        zoom: 8,
        center: latlng
    };

    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

    // Call the codeAddress function (once) when the map is idle (ready)
    google.maps.event.addListenerOnce(map, 'idle', codeAddress);
}

function codeAddress() {

    // Define address to center map to
    var address = 'Paris, France';

    geocoder.geocode({
        'address': address
    }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            // Center map on location
            map.setCenter(results[0].geometry.location);

            // Add marker on location
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

        } else {

            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

initialize();

JSFiddle demo

JSFiddle demo

Edit:of course you can geocode a complete address like this:

编辑:当然,您可以像这样对完整地址进行地理编码:

// Define address to center map to
var address = 'Rue Casse-Cul, Montboucher-sur-Jabron, France';