Подтвердить что ты не робот

PHP - получить широту и долготу с адреса

Я использовал автозаполнение геокода, но когда я выбираю из раскрывающегося списка, он дает мне лат и длинный адрес

Мне нужно проверить, когда lat и long пустые, а затем из опубликованного адреса я должен получить широту и долготу

4b9b3361

Ответ 1

предположим, что у вас есть скрытое значение для lat и long mapLat и mapLong и имя поля ввода - это местоположение то вы можете проверить, как показано ниже

<html>
<form>
<input type="hidden" name="mapLat">
<input type="hidden" name="mapLong">
<input type="text" name="location">
<input type="submit" name="submit" value="submit">
</form>
</html>



extact($_POST);
if($mapLat =='' && $mapLong ==''){
        // Get lat long from google
        $latlong    =   get_lat_long($location); // create a function with the name "get_lat_long" given as below
        $map        =   explode(',' ,$latlong);
        $mapLat         =   $map[0];
        $mapLong    =   $map[1];    
}


// function to get  the address
function get_lat_long($address){

    $address = str_replace(" ", "+", $address);

    $json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");
    $json = json_decode($json);

    $lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
    $long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
    return $lat.','.$long;
}

Ответ 2

Попробуйте это для получения адреса

<?
function getaddress($lat,$lng)
{
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
$json = @file_get_contents($url);
$data=json_decode($json);
$status = $data->status;
if($status=="OK")
return $data->results[0]->formatted_address;
else
return false;
}


$lat= 26.754347; //latitude
$lng= 81.001640; //longitude
$address= getaddress($lat,$lng);
if($address)
{
echo $address;
}
else
{
echo "Not found";
}

?>

Ответ 3

Использование CURL

<?php
$address = "Kathmandu, Nepal";
$url = "http://maps.google.com/maps/api/geocode/json?address=".urlencode($address);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
$responseJson = curl_exec($ch);
curl_close($ch);

$response = json_decode($responseJson);

if ($response->status == 'OK') {
    $latitude = $response->results[0]->geometry->location->lat;
    $longitude = $response->results[0]->geometry->location->lng;

    echo 'Latitude: ' . $latitude;
    echo '<br />';
    echo 'Longitude: ' . $longitude;
} else {
    echo $response->status;
    var_dump($response);
}    
?>

Ответ 4

// We define our address
$address = 'Indore, MP 452001';
echo"<PRE>";
print_r(get_lat_long($address));

// function to get  the address
function get_lat_long($address) {
   $array = array();
   $geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');

   // We convert the JSON to an array
   $geo = json_decode($geo, true);

   // If everything is cool
   if ($geo['status'] = 'OK') {
      $latitude = $geo['results'][0]['geometry']['location']['lat'];
      $longitude = $geo['results'][0]['geometry']['location']['lng'];
      $array = array('lat'=> $latitude ,'lng'=>$longitude);
   }

   return $array;
}

Ответ 5

Я пробовал описанные выше решения, но ни одно из них не работало, затем я попытался исправить самостоятельно, поэтому ниже приведен правильный код:

    $going=$this->input->post('going');

    $address =$going; // Google HQ
    $prepAddr = str_replace(' ','+',$address);
    $apiKey = 'Add your API Key'; // Google maps now requires an API key.

    $geocode=file_get_contents('https://maps.googleapis.com/maps/api/geocode/json? 
   address='.urlencode($address).'&sensor=false&key='.$apiKey);

    //print_r($geocode);

    $output= json_decode($geocode);
    $latitude = $output->results[0]->geometry->location->lat;
    $longitude = $output->results[0]->geometry->location->lng;