How to get nearest cities with Google Nearby API?

312 views Asked by At

I'm working in a project where I should display all cities (locality) around 20km from a device location using lat,long.

Moreove, the locality of the device location is not on the result.

Could someone help me?

I precise that I'm not a developer.

Many thanks for your help!

I tried the request below on Postman, but I only have two results rather than more than 10.

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=48.7707452,2.0803735&radius=20000&type=locality&key=AIzxxxxxxE

Below is the response:

`

{
    "html_attributions": [],
    "results": [
        {
            "geometry": {
                "location": {
                    "lat": 48.801408,
                    "lng": 2.130122
                },
                "viewport": {
                    "northeast": {
                        "lat": 48.82857804347341,
                        "lng": 2.168480543860636
                    },
                    "southwest": {
                        "lat": 48.77916591232869,
                        "lng": 2.069908968772275
                    }
                }
            },
            "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/geocode-71.png",
            "icon_background_color": "#7B9EB0",
            "icon_mask_base_uri": "https://maps.gstatic.com/mapfiles/place_api/icons/v2/generic_pinlet",
            "name": "Versailles",
            "photos": [
                {
                    "height": 3024,
                    "html_attributions": [
                        "<a href=\"https://maps.google.com/maps/contrib/116593793480207812084\">Jessy Velazquez</a>"
                    ],
                    "photo_reference": "AUjq9jkmbt7CKGCwJfn3ZlpLVC-wGt_1svXYWTyA5p9pgcmd6XCNbEcwAFFjF0xe2tuLIYm5F_42s0Q4dbI0ifJTHZy5-gfzQfSo2jMp_ATL-WfPl3jJHf8WbnRVLSslBCKg3j5jYQBU2pkyb2Tjkk7PLZSGSuv9ycLQu-j2zTBWUM9x-ejT",
                    "width": 4032
                }
            ],
            "place_id": "ChIJvSD0dbR95kcRukqEDa0AnoY",
            "reference": "ChIJvSD0dbR95kcRukqEDa0AnoY",
            "scope": "GOOGLE",
            "types": [
                "locality",
                "political"
            ],
            "vicinity": "Versailles"
        },
        {
            "geometry": {
                "location": {
                    "lat": 48.7738734,
                    "lng": 2.0360157
                },
                "viewport": {
                    "northeast": {
                        "lat": 48.7992215538692,
                        "lng": 2.055979168810353
                    },
                    "southwest": {
                        "lat": 48.75589319907799,
                        "lng": 1.994393632933018
                    }
                }
            },
            "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/geocode-71.png",
            "icon_background_color": "#7B9EB0",
            "icon_mask_base_uri": "https://maps.gstatic.com/mapfiles/place_api/icons/v2/generic_pinlet",
            "name": "Montigny-le-Bretonneux",
            "photos": [
                {
                    "height": 4160,
                    "html_attributions": [
                        "<a href=\"https://maps.google.com/maps/contrib/100080658394344210444\">ali imoune</a>"
                    ],
                    "photo_reference": "AUjq9jn0-yeBGJe57tERWIrudEEdhV_zdqrrtGna1VvH-vI33q2FMfh7c_YaZpK4VXR1eWFhU7MYt0rhxZujTMnM3DL7F5vOXX0zepVThDaB_I5gZ0Io2RjnXbYh4ZDInZ-0aXDY-w4xdisBO_4oAAVgot1516GAbE-He8jvgCacDUcp03w1",
                    "width": 3120
                }
            ],
            "place_id": "ChIJDxMIwS-B5kcRHthZxYnQcNo",
            "reference": "ChIJDxMIwS-B5kcRHthZxYnQcNo",
            "scope": "GOOGLE",
            "types": [
                "locality",
                "political"
            ],
            "vicinity": "Montigny-le-Bretonneux"
        }
    ],
    "status": "OK"
}`
1

There are 1 answers

1
Yrll On

type=locality is not supported by Nearby Search of Places API

Please see Place Types Documentation.

As you can see on the documentation, the types=locality is only available in Table 2 and 3:

The Place type values in Table 2 are used in the following ways:

  • As part of the result of a Place details request (for example, a call to fetchPlace()), or anywhere a Place result is returned. The request must specify the appropriate "types" data field.
  • As part of an Autocomplete place prediction. For more information on the rules for using these values, see Places Autocomplete.
  • To denote address components.

ref: https://developers.google.com/maps/documentation/places/web-service/supported_types#table2

There's a note there that such types are not supported in the type filter of a place search.

This begs us the question...

How to get the nearest cities?

To be able to get nearby cities using Places API, you can use the Place Autocomplete of Places API.

The Place Autocomplete also have the types, radius, and location parameters that you can use just like the Nearby Search.

But since Place Autocomplete is designed to respond to user input and requires an input parameter, your users still needs to put something before sending a request.

Here's an example request:

https://maps.googleapis.com/maps/api/place/autocomplete/json?
input={INPUT_ANY_CITY_HERE_WITHIN_20KM_OF_LOCATION}
&location=48.7707452,2.0803735
&radius=20000
&strictbounds=true
&types=(cities)
&key=YOUR_API_KEY

Note: I included strictbounds to return only those places that are strictly within the region defined by location and radius. This is a restriction, rather than a bias, meaning that results outside this region will not be returned even if they match the user input.

The request will only return cities within the circle of this sample map:

function initMap() {
  // Create the map.
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 10,
    center: {lat:48.7707452, lng: 2.0803735},
    mapTypeId: "terrain",
  });

    const cityCircle = new google.maps.Circle({
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35,
      map: map,
      center: {lat:48.7707452, lng: 2.0803735},
      radius: 20000, 
    });
  }

window.initMap = initMap;
/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<html>
  <head>
    <title>Circles</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!-- 
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

Hope this helps!