Google maps API geolocation + radar places search

筅森魡賤 提交于 2019-12-02 07:35:06

Because of async call to navigator.geolocation.getCurrentPosition() which returns immediately, location property of request is undefined. Call to

service.nearbySearch(request,callback);

complains that location is missing. And that is true because pos is not set at that moment.

You have to move this part of code:

        var request = {
            location:pos,
            radius:500,
            types: ['store']
        };

        infowindow = new google.maps.InfoWindow();
        var service = new google.maps.places.PlacesService(map);
        service.nearbySearch(request,callback);

to

    navigator.geolocation.getCurrentPosition(function(position) {
    ...
            map.setCenter(pos);

and make variable infoWindow global.

This is changed initialize() function:

var map;
var service;
var marker;
var pos;
var infowindow;


function initialize() {

    var mapOptions = {
        zoom: 15
    };

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

    // Try HTML5 geolocation
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            pos = new google.maps.LatLng(position.coords.latitude,
                                         position.coords.longitude);

            infowindow = new google.maps.InfoWindow({
                map: map,
                position: pos,
                content: 'Located'
            });

            map.setCenter(pos);

            var request = {
                location:pos,
                radius:500,
                types: ['store']
            };

            infowindow = new google.maps.InfoWindow();
            var service = new google.maps.places.PlacesService(map);
            service.nearbySearch(request,callback);
        }, function() {
            handleNoGeolocation(true);
        });
    } else {
        // Browser doesn't support Geolocation
        handleNoGeolocation(false);
    }

    function callback(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            for (var i = 0; i < results.length; i++) {
                console.log('after / to createMarker');
                createMarker(results[i]);
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!