简体   繁体   中英

Nearby Places Google Maps Places API

First of all, I just started with JavaScript, so I'm not really good at it. I am making an app, using the Google Maps Places API, in which you can push a button and get your location, push another button and get nearby places (for example stores or bars) based on your location. Getting the location of the device works, but my code doesn't display the nearby places. It does go to the location, but it doesn't show the markers of the nearby places. I don't know what is going wrong, but I think it might have to do with the code for the markers or with the sequence of the code.

I am using Intel XDK (HTML5 + Cordova and the App Designer) and the Google Maps Places API. Right now it all happens when one button (with id="myloc-btn") is pushed, but (if both the location and the nearby places work) I want to seperate them in two buttons, one to show the location and one to show the nearby places.

Below is my javascript code. I have commented out the marker for the location of the device I originally had, because I thought it might be in the way of the markers for the nearby places.

Anyone know what's wrong or can help me?

Thanks in advance!

---UPDATE---

I tried the search nearby places from the Google Maps documentation ( https://developers.google.com/maps/documentation/javascript/examples/place-search ), with a set location (I basically copied and pasted the code), but that doesn't work either. Again it goes to the right location, but it doesn't display any markers. I tried it both in the simulator and on my phone, but it both has the same result. I don't know why the markers don't show

var map;
var service;
var infoWindow;
var pos;
var marker = [];
//var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//var labelIndex = 0;

function register_event_handlers() {

$(document).on("click", "#myloc-btn", function(evt) {
    initMap();
});

 function initMap() {
    map = new google.maps.Map(document.getElementById('gmap'), {zoom: 14});

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
      pos = {
            lat: position.coords.latitude, 
            lng: position.coords.longitude
      };
      //addMarker(pos, map);
      map.setCenter(pos);
     }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
     } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
     }

     var request = {
        location: pos,
        radius: 5000,
        type: ['store']
      };
      infowindow = new google.maps.InfoWindow();
      var service = new google.maps.places.PlacesService(map);
      service.nearbySearch(request, callback); 

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

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
  }

 /*
 function addMarker(location, map) {
        var marker = new google.maps.Marker({
            map: map,
            // Define the place with a location, a query string and a label.
            place: {
                location: location,
                query: 'This is my location'
            },
            label: labels[labelIndex++ % labels.length],
        });

        // Construct a new InfoWindow.
        var infoWindow = new google.maps.InfoWindow({
            content: 'Here I am!'
        });

        // Opens the InfoWindow when marker is clicked.
        marker.addListener('click', function() {
            infoWindow.open(map, marker);
        }); 
 }
 */ 


 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);
        });
 }

 document.addEventListener("app.Ready", register_event_handlers, false);
 })();

In the callback provided to getCurrentPosition() , you're setting pos . However, this callback will get called after the phone has determined the location, ie at some random point in the future. Which is long after you're trying to use that pos in your request for the places. You need to move the places code in its own function, then call it while passing the map and pos , after you have centered the map. Almost exactly what you already did with addMarker() .

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