HTML - Javascript - 结合地理编码和附近搜索

时间:2017-04-17 09:08:25

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

我正在尝试将Google地理编码和附近搜索结合在一个搜索框中。

用户将键入他的地址,地图应显示他附近的所有酒吧。

initmap功能:

function initMap() {
    var setMap = new google.maps.LatLng(50, 9398252, 6.93936825);
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 15,
        center: setMap
    });

    var request = {
        location: setMap,
        radius: '5000',
        types: ['bar']
    };

    var geocoder = new google.maps.Geocoder();

    document.getElementById('submit').addEventListener('click', function() {
        geocodeAddress(geocoder, map);
    });

}

这是我的地理编码功能:

function geocodeAddress(geocoder, resultsMap) {
    var address = document.getElementById('address').value;
    geocoder.geocode({ 'address': address }, function(results, status) {
        if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);

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

这就是我创建Marker的方法:

function callback(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
            createMarker(results[i]);
        }
    }
}

function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
    });
}

以下是我的搜索框:

<form class="navbar-form navbar-left">
    <div class="form-group">
        <div id="floating-panel">
            <input id="address" type="textbox" value="Cologne, Germany" class="form-control">
            <input id="submit" type="button" value="Search" class="form-control">
        </div>
    </div>
</form>

到现在为止我可以搜索一个地址,所以我的地理编码器应该可以工作。 我只是不知道如何在我的代码中涉及附近的搜索过程.. 希望有人可以帮我解决我的问题。

1 个答案:

答案 0 :(得分:0)

收到Geocoding API的结果后,您可以调用PlacesService API。知道每次调用API都是异步的,你必须等待Geocoding回调才能启动PlaceService API。

看起来像:

function geocodeAddress(geocoder, resultsMap) {
    var address = document.getElementById('address').value;
    var service;
    geocoder.geocode({'address': address}, function(results, status) {
        if (status === 'OK') {
            resultsMap.setCenter(results[0].geometry.location);
            service = new google.maps.places.PlacesService(resultsMap);
            service.nearbySearch({ location: results[0].geometry.location, radius: 500, type: [ 'bar' ] }, PlaceServiceCallBack); // where PlaceServiceCallBack handles the markers creation
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}