Привет, что такое formulla, чтобы получить долготу и широту любого адреса, если у меня есть имя улицы, имя_пользователя, имя города, имя_пользователя и почтовый индекс в PHP? Благодаря
Как получить долготу и широту любого адреса?
Ответ 1
Используйте следующий код для получения lat и long используя php. Вот два метода:
Type-1:
<?php
// Get lat and long by address
$address = $dlocation; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
?>
изменить - запросы Google Карт должны превышать https
Type-2:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(50.804400, -1.147250);
var mapOptions = {
zoom: 6,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
}
function codeAddress(address,tutorname,url,distance,prise,postcode) {
var address = address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow = new google.maps.InfoWindow({
content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
});
infowindow.open(map,marker);
} /*else {
alert('Geocode was not successful for the following reason: ' + status);
}*/
});
}
google.maps.event.addDomListener(window, 'load', initialize);
window.onload = function(){
initialize();
// your code here
<?php foreach($addr as $add) {
?>
codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
<?php } ?>
};
</script>
<div id="map-canvas12"></div>
Ответ 2
<?php
$address = 'BTM 2nd Stage, Bengaluru, Karnataka 560076'; // Address
$apiKey = 'api-key'; // Google maps now requires an API key.
// Get JSON results from this request
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.$apiKey);
$geo = json_decode($geo, true); // Convert the JSON to an array
if (isset($geo['status']) && ($geo['status'] == 'OK')) {
$latitude = $geo['results'][0]['geometry']['location']['lat']; // Latitude
$longitude = $geo['results'][0]['geometry']['location']['lng']; // Longitude
}
?>
Ответ 3
Вы должны взглянуть на библиотеку Geocoder PHP5:)
Ответ 4
Вам необходимо получить доступ к службе геокодирования (т.е. от Google), нет простой формулы для переноса адресов в геокоординаты.
Ответ 5
Для этого вы можете использовать API Карт Google. Подробнее см. В блоге ниже.
http://stuff.nekhbet.ro/2008/12/12/how-to-get-coordinates-for-a-given-address-using-php.html
Ответ 6
В PHP есть несколько полезных встроенных функций для получения географического местоположения. Возможно, посмотрите здесь: http://php.net/manual/en/ref.geoip.php
Согласно руководству php, "для этого расширения требуется установка библиотеки GeoIP C версии 1.4.0 или выше. Вы можете получить последнюю версию с http://www.maxmind.com/app/c и скомпилировать его самостоятельно.
Ответ 7
Я придумал следующее, которое учитывает потерю мусора и ошибки file_get_contents....
function get_lonlat( $addr ) {
try {
$coordinates = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($addr) . '&sensor=true');
$e=json_decode($coordinates);
// call to google api failed so has ZERO_RESULTS -- i.e. rubbish address...
if ( isset($e->status)) { if ( $e->status == 'ZERO_RESULTS' ) {echo '1:'; $err_res=true; } else {echo '2:'; $err_res=false; } } else { echo '3:'; $err_res=false; }
// $coordinates is false if file_get_contents has failed so create a blank array with Longitude/Latitude.
if ( $coordinates == false || $err_res == true ) {
$a = array( 'lat'=>0,'lng'=>0);
$coordinates = new stdClass();
foreach ( $a as $key => $value)
{
$coordinates->$key = $value;
}
} else {
// call to google ok so just return longitude/latitude.
$coordinates = $e;
$coordinates = $coordinates->results[0]->geometry->location;
}
return $coordinates;
}
catch (Exception $e) {
}
затем, чтобы получить шнуры: где $pc - почтовый индекс или адрес. $ address = get_lonlat ($ pc); $ l1 = $address- > lat; $ l2 = $address- > lng;
Ответ 8
Нет форума, поскольку названия улиц и города в основном раздаются случайным образом. Адрес необходимо искать в базе данных. Кроме того, вы можете искать почтовый индекс в базе данных для региона, для которого предназначен почтовый индекс.
Вы не упомянули страну, поэтому я собираюсь предположить, что вам просто нужны адреса в США. Существует множество баз данных, которые вы можете использовать, некоторые бесплатные, некоторые нет.
Вы также можете использовать API Карт Google, чтобы они искали адрес в своей базе данных для вас. Это, вероятно, самое простое решение, но требует, чтобы ваше приложение постоянно работало в Интернете.
Ответ 9
Для адресов в США вы можете использовать Geocoder, эта страница справки содержит несколько примеров кода на разных языках, чтобы вы начали.