如何直接从Google地图而不是地方获取对象

时间:2015-07-02 11:24:56

标签: javascript google-maps google-maps-api-3

我想获取地图对象的坐标(机场门)。

我不能使用Places API,因为gate不是Places对象。

如果您打开maps.google.com并输入SFO Gate 27,则无法找到它,但如果您输入SFO,请按Enter键,然后键入Gate 27,您将找到正确的位置。

所以,我的问题是如何使用JS SDK或HTTP请求找到这些地方?

1 个答案:

答案 0 :(得分:1)

使用地理编码器。

var geocoder;
var map;

function initialize() {

    map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 5,
        center: new google.maps.LatLng(10, 10)
    });

    geocoder = new google.maps.Geocoder();

    // Bind click event listener for search button
    document.getElementById("search").addEventListener('click', codeAddress, false);

    // Bind key-up event listener for address field
    document.getElementById("address").addEventListener('keyup', function (event) {

        // Check the event key code
        if (event.keyCode == 13) {

            // Key code 13 == Enter key was pressed (and released)
            codeAddress();
        }
    });
}

function codeAddress() {

    // Get address and geocode
    var address = document.getElementById("address").value;

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

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

            // Center map on result bounds
            map.fitBounds(results[0].geometry.bounds);

            // Place marker on map
            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