How can I get city name from a latitude and longitude point?

后端 未结 11 1220
感情败类
感情败类 2020-11-28 03:07

Is there a way to get a city name from a latitude and longitude point using the google maps api for javascript?

If so could I please see an example?

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 03:31

    you can do it with pure php and google geocode api

    /*
     *
     * @param latlong (String) is Latitude and Longitude with , as separator for example "21.3724002,39.8016229"
     **/
    function getCityNameByLatitudeLongitude($latlong)
    {
        $APIKEY = "AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Replace this with your google maps api key 
        $googleMapsUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latlong . "&language=ar&key=" . $APIKEY;
        $response = file_get_contents($googleMapsUrl);
        $response = json_decode($response, true);
        $results = $response["results"];
        $addressComponents = $results[0]["address_components"];
        $cityName = "";
        foreach ($addressComponents as $component) {
            // echo $component;
            $types = $component["types"];
            if (in_array("locality", $types) && in_array("political", $types)) {
                $cityName = $component["long_name"];
            }
        }
        if ($cityName == "") {
            echo "Failed to get CityName";
        } else {
            echo $cityName;
        }
    }
    

提交回复
热议问题