How do I get names of cities that are around me with API on a remote server?

Asked

Viewed 1,002 times

2

Currently I use the lines of code below to list the city where I am through latitude and longitude, however, with the same coordinates, I want to list also the cities that are around, by mileage for example. Is it possible? I did a lot of research on this but couldn’t find a solution.

Follow the code I’m using to pull the current city:

 $latitude = htmlspecialchars($_GET["latitude"]);
       $longitude = htmlspecialchars($_GET["longitude"]); 
       $geocode = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$latitude.','.$longitude.'&sensor=false');
        $resultado = json_decode($geocode);


          for($j=0;$j<count($resultado->results[0]->address_components);$j++){
               $cn=array($resultado->results[0]->address_components[$j]->types[0]);
           if(in_array("locality", $cn))
           {
            $s = $resultado->results[0]->address_components[$j]->long_name;
           }
            } 

I would appreciate it if you would help me find a solution.

  • 1

    If the selected answer served, I would suggest taking Google and Google Maps from the tags and title of the question, because the answer does not get the results from Google.

1 answer

4


I found a post that combines Google Maps Geocoding API with Geonames.org API to do what you want, follow below the code . php

$geocodeObject = json_decode(file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address={CITY NAME},{COUNTRY CODE}'), true);

//Pegar a latitude e longitude
$latitude = $geocodeObject['results'][0]['geometry']['location']['lat'];
$longitude = $geocodeObject['results'][0]['geometry']['location']['lng'];

//Entrar com os parametros
$responseStyle = 'short';
$citySize = 'cities15000'; //Voce ainda pode definir um numero minimo de habitantes por cidades
$radius = 30; // Raio em KM
$maxRows = 30;
$username = '{YOUR USERNAME}'; //Seu USERNAME no GeoNames

$nearbyCities = json_decode(file_get_contents('http://api.geonames.org/findNearbyPlaceNameJSON?lat='.$latitude.'&lng='.$longitude.'&style='.$responseStyle.'&cities='.$citySize.'&radius='.$radius.'&maxRows='.$maxRows.'&username='.$username, true));

foreach($nearbyCities->geonames as $cityDetails)
{

}

Source: https://stackoverflow.com/questions/10172084/can-i-use-google-api-for-finding-nearest-cities

I hope I’ve helped :)

Att. Jeiferson

  • worked perfectly, thank you...

  • 1

    I saw no advantage in taking the coordinates from google, since it will use Geonames to get the neighboring cities. Could get everything from Geonames directly.

  • That’s exactly what I did, since the ones who send the coordinates to the server are the mobile devices. So from the line $responseStyle = 'short'; the code solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.