Есть вопрос?
Зайди на форум

Поиск на сайте: Advanced

Denix - новый дистрибутив Linux. Русификация Ubuntu и установка кодеков

dkws.org.ua
Форум сайта dkws.org.ua
 
Главная    ТемыТемы    АльбомАльбом    РегистрацияРегистрация 
 ПрофильПрофиль   Войти и проверить личные сообщенияВойти и проверить личные сообщения   ВходВход 

Получение адреса из Google Maps (JSON/PHP)

 
Начать новую тему Ответить на тему    Список форумов dkws.org.ua -> PHP
 
Автор Сообщение
den

Старожил


Зарегистрирован: 31.01.2006
Сообщения: 13870
Откуда: Кировоград, Украина

СообщениеДобавлено: Чт Мар 05, 2020 11:18 am    Заголовок сообщения: Получение адреса из Google Maps (JSON/PHP)
Ответить с цитатой

<?php class GoogleClass { public function getAddressFromGoogleMaps($lat, $lon) { $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false"; // Make the HTTP request $data = @file_get_contents($url); // Parse the json response $jsondata = json_decode($data, true); // If the json data is invalid, return empty array if (!$this->check_status($jsondata)) {
return array();
}

$address = array(
'country' => $this->google_getCountry($jsondata),
'province' => $this->google_getProvince($jsondata),
'city' => $this->google_getCity($jsondata),
'street' => $this->google_getStreet($jsondata),
'postal_code' => $this->google_getPostalCode($jsondata),
'country_code' => $this->google_getCountryCode($jsondata),
'formatted_address' => $this->google_getAddress($jsondata),
);

return $address;
}

//Check if the json data from Google Geo is valid
public function check_status($jsondata) {
if ($jsondata["status"] == "OK") {
return true;
}

return false;
}

//Given Google Geocode json, return the value in the specified element of the array
public function google_getCountry($jsondata) {
return $this->findLongNameGivenType("country", $jsondata["results"][0]["address_components"]);
}
public function google_getProvince($jsondata) {
return $this->findLongNameGivenType("administrative_area_level_1", $jsondata["results"][0]["address_components"], true);
}
public function google_getCity($jsondata) {
return $this->findLongNameGivenType("locality", $jsondata["results"][0]["address_components"]);
}
public function google_getStreet($jsondata) {
return $this->findLongNameGivenType("street_number", $jsondata["results"][0]["address_components"]) . ' ' . $this->findLongNameGivenType("route", $jsondata["results"][0]["address_components"]);
}
public function google_getPostalCode($jsondata) {
return $this->findLongNameGivenType("postal_code", $jsondata["results"][0]["address_components"]);
}
public function google_getCountryCode($jsondata) {
return $this->findLongNameGivenType("country", $jsondata["results"][0]["address_components"], true);
}
public function google_getAddress($jsondata) {
return $jsondata["results"][0]["formatted_address"];
}


// Searching in Google Geo json, return the long name given the type.
// (If short_name is true, return short name)
public function findLongNameGivenType($type, $array, $short_name = false) {
foreach ($array as $value) {
if (in_array($type, $value["types"])) {
if ($short_name) {
return $value["short_name"];
}

return $value["long_name"];
}
}
}

https://think201.com/blog/2017/google-api-maps-php/

JS/Axios https://stackoverflow.com/questions/46941447/extract-formatted-address-from-json-return-from-google-maps-api

componentWillMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
}, () => this.getGeocode()); // call the api after getCurrentPosition is finished
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000 },
);

}
getGeocode() {
axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ this.state.latitude +','+ this.state.longitude +'&key=__API_KEY__') // be sure your api key is correct and has access to the geocode api
.then(response => {
console.log(response);
this.setState({
place: response.data.results[0].formatted_address // access from response.data.results[0].formatted_address
})
}).catch((error) => { // catch is called after then
this.setState({ error: error.message })
});
}
Вернуться к началу
Посмотреть профиль Отправить личное сообщение dhsilabs@jabber.ru
Показать сообщения:   
Начать новую тему Ответить на тему    Список форумов dkws.org.ua -> PHP Часовой пояс: GMT
Страница 1 из 1
 Главная страница сайта
 
Перейти:  
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
© Колисниченко Денис