Jose Osorio
Jose Osorio

Reputation: 939

Google places use viewport instead of radius

How can I use the viewport to find places with google maps api instead of radius, the radius method is not much accurate for me.

I.e. I used the type restriction to only get nigh_club within a 50.000 meters radius in london and I did not get ministry of sound in my markers.

If anyone have a suggestion about how to refine and place request I will be glad.

NOTE: search request

var request = {
  location: location,
  radius: 3000,
  //types: ['night_club, bar']
  keyword: 'night+club'
};

Upvotes: 0

Views: 1392

Answers (2)

Diego Velez
Diego Velez

Reputation: 1893

You can get the current viewport radius using this function

What I'm doing here is getting the center and the northeast point of the current viewport in google maps, then I calculate the distance between those two points and that's it. The result is given in meters

var bounds = window.map.getBounds();
var ne_bounds = bounds.getNorthEast();
var center = bounds.getCenter();
var radius = google.maps.geometry.spherical.computeDistanceBetween(center, ne_bounds);

You can also check this by creating a circle like this

function draw_map_bounds_circle() {
  var bounds = window.map.getBounds();
  var ne_bounds = bounds.getNorthEast();
  var circle_center = bounds.getCenter();
  var circle_radius = google.maps.geometry.spherical.computeDistanceBetween(circle_center, ne_bounds);
  
  const newCircle = new google.maps.Circle({
    strokeColor: "#7CA0C0",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#7CA0C0",
    fillOpacity: 0.35,
    map: window.map,
    center: circle_center,
    radius: circle_radius
  });
}

NOTE: make sure you import the geometry library from google maps API. ref. https://developers.google.com/maps/documentation/javascript/geometry

Upvotes: 0

victmo
victmo

Reputation: 1216

Use LatLngBounds to define your location based on the SW and NE coordinates that define your viewport, instead of LatLng + radius.

var viewport = new google.maps.LatLngBounds(
    new google.maps.LatLng(southLat, westLng), // SW
    new google.maps.LatLng(northLat, eastLng)  // NE
);

var request = {
    location: viewport,
    // types: ['night_club', 'bar'] 
    keyword: 'night club'
};

https://developers.google.com/maps/documentation/javascript/reference#LatLngBounds

Upvotes: 1

Related Questions