Place Searches

by Lawrence Ross

HTML

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

CSS

html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

var map;
var service;
var infowindow;
var resultsArray = [];
var bounds;

function initMap() {
  bounds = new google.maps.LatLngBounds();
  infowindow = new google.maps.InfoWindow();
  map = new google.maps.Map(
    document.getElementById('map'));

  var points = [
    [2.627365, 49.215369],
    [2.760591, 49.647163],
    [2.952975, 50.057504],
    [3.344742, 50.280862],
    [3.768293, 50.451306],
    [4.21659, 50.534029]
  ]
  var i = 0;
  for (point of points) {
    googlePlaces(point, i);
    i++;
  }
  setTimeout(function() {
    console.log(resultsArray);
  }, 10000);

}


function googlePlaces(point, index) {
  var latLng = new google.maps.LatLng(point[1], point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
    
      resultsArray[index] = results; // ...then hits this code [i] times

      for (var i = 0; i < results.length; i++) {
        var marker = createMarker(results[i], "search " + index);
        bounds.extend(marker.getPosition());
      }
      map.fitBounds(bounds);
    }
  })
}

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

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(text + "<br>" + place.name);
    infowindow.open(map, this);
  });
  return marker;
}