0

I have this query

var service = new google.maps.places.PlacesService(map);
var request = {
  location: currentLocation,
  radius: '4828.03',
  type: ['workout gyms']
};
service.nearbySearch(request, callback);

And I am able to successfully place a marker on every location, but I want to make the marker clickable such that it displays the placeID in an infoWindow when clicked. Does anyone know how I could do this?

Matt X
  • 224
  • 1
  • 6
  • 17

1 Answers1

1

Modified code from the related question: Place nearbySearch Callback doesn't iterate through all elements (to return place details)

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    console.log("nearbySearch returned " + results.length + " results")
    for (var i = 0; i < results.length; i++) {
      // make a marker for each "place" in the result
      createMarker(results[i]);
    }
  } else console.log("error: status=" + status);
}


function createMarker(place) {
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });
  google.maps.event.addListener(marker, 'click', function() {
    // display the place "name" and "place_id" in the infowindow.
    infowindow.setContent(place.name + "<br>" + place.place_id);
    infowindow.open(map, this);
  });
}

modified fiddle

screenshot of resulting map

code snippet:

function initMap() {
  var lng;
  var lat;
  var my_loc = new google.maps.LatLng(37.4419, -122.1419);
  map = new google.maps.Map(document.getElementById('map'), {
    center: my_loc,
    zoom: 10
  });
  geocoder = new google.maps.Geocoder();
  infowindow = new google.maps.InfoWindow();
  service = new google.maps.places.PlacesService(map);
  var request = {
    location: map.getCenter(),
    radius: 4828.03,
    type: ['workout gyms']
  };
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    console.log("nearbySearch returned " + results.length + " results")
    for (var i = 0; i < results.length; i++) {
      var id = results[i].place_id;
      createMarker(results[i]);
    }
  } else console.log("error: status=" + status);
}


function createMarker(place) {
  console.log("adding place " + place.name + " loc=" + place.geometry.location.toUrlValue(6));
  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 + "<br>" + place.place_id);
    infowindow.open(map, this);
  });
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245