简体   繁体   中英

Nearby places in google maps APIs

I am trying to write a program in javascript related to finding my place by using google maps APIs and the browser navigator and then put a marker on the place.My code works properly for this part. But for the second part that I want to find the nearby places and put markers on them does not work and I cannot find the problem. It gives me an error about the map variable. It seems the code breaks and cannot get the map variable for performsearch function. Any idea would be highly appreciated? The code is as below:

<!DOCTYPE html>
 <html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
            html { height: 100% }
            body { height: 100%; margin: 0; padding: 0 }
            #map-canvas { height: 75% }
        </style>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC2MndnCGBXqDolsrQYhNdVyXqsk0NRm8Q&sensor=true&libraries=places">
        </script>
        <script type="text/javascript" >
        var map;

            function handleSearchResults(results, status)
           {
               console.log(results);
               document.write

           if (status == google.maps.places.PlacesServiceStatus.OK)
                       {

                   for(var i = 0; i<results.length; i++)
                               {
                           var marker = new google.maps.Marker(
                                       {
                                   position: results[i].geometry.Location,
                               map:map,
                               icon: results[i].icon
                               });
                       }      
                  }

           }
        function performSearch()
            {

                var request = {
            bounds: map.getBounds(),
            name: "McDonald's"
            };

            var service = new google.maps.places.PlacesService(map);
                service.nearbySearch(request, handleSearchResults(results, status));

           }

           function initialize(location) 
               {
               var myLatlng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);

                   var mapOptions = 
                       {
                           center: myLatlng,
                           zoom: 9
                       };
                   var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
           var marker = new google.maps.Marker(
                       {
                   position: myLatlng,
               map: map,
               title: "My place"
               }); 

           service = new google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch());
              }



      $(document).ready(function()
          {
              navigator.geolocation.getCurrentPosition(initialize);
          });
        </script>
    </head>
    <body>
        <div id="map-canvas"/>
    </body>
</html>

There are several issues. Fixed code(modifications are commented inside):

var map;

function handleSearchResults(results, status) {

    if (status == google.maps.places.PlacesServiceStatus.OK) {

        for (var i = 0; i < results.length; i++) {
            var marker = new google.maps.Marker({
                //typo: it must be location not Location
                position: results[i].geometry.location,
                map: map,
                icon: results[i].icon
            });
        }
    }

}

function performSearch() {

    var request = {
        bounds: map.getBounds(),
        name: "McDonald's"
    };

    var service = new google.maps.places.PlacesService(map);
    //use only the name of the function as callback-argument
    service.nearbySearch(request, handleSearchResults);

}

function initialize(location) {
    var myLatlng = new google.maps.LatLng(location.coords.latitude, 
                                          location.coords.longitude);

    var mapOptions = {
        center: myLatlng,
        zoom: 9
    };
    //removed the var-keyword(otherwise map is not global accessible)
    map = new google.maps.Map(document.getElementById("map-canvas"), 
                              mapOptions);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: "My place"
    });
    //again: use only the name of the function as callback-argument
    service = new google.maps.event.addListenerOnce(map, 
                                                    'bounds_changed', 
                                                     performSearch);
}



$(document).ready(function () {
    navigator.geolocation.getCurrentPosition(initialize);
});

But note: geolocating may fail, currently the map will never be initialized when it fails. You better separate the map-creation from the geolocating

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM