简体   繁体   中英

php address into latitude and longitude

i am trying to convert the address into latitude.here's my code. but its giving wrong latititude. if i put the address manually at $final place it gives the correct latitude.however i cant hard code it,whatever source comes in text box i have to find out that address latitude. what is the mistake?

<?php 
    $source=$_POST['textfield11'];
    $dest=$_POST['textfield12'];
    $time=$_POST['textfield13'];
    $only = str_replace(',', '+', $source);
    $final = str_replace(' ', '+', $only);

    $url='http://maps.googleapis.com/maps/api/geocode/json?address=$final&sensor=false';
    $source1 = file_get_contents($url);
    $obj = json_decode($source1);
    $LATITUDE = $obj->results[0]->geometry->location->lat;
    echo $LATITUDE;
?>

Instead of using str_replace , you should use urlencode .

<?php 
$source=urlencode($_POST['textfield11']);
$dest=$_POST['textfield12'];
$time=$_POST['textfield13'];

$url='http://maps.googleapis.com/maps/api/geocode/json?address=$source&sensor=false';
$source1 = file_get_contents($url);
$obj = json_decode($source1);
$LATITUDE = $obj->results[0]->geometry->location->lat;
echo $LATITUDE;
?>
<?
$final = urlencode($source);
$geo = simplexml_load_file("http://maps.google.com/maps/api/geocode/xml?address={$final}&sensor=false");
$lat = $geo->result->geometry->location->lat;
$lng = $geo->result->geometry->location->lng;
?>

Add a space after your , in the str_replace ... Cos at the moment, if the user types an address as "Somewhere road, That town" it will replace the ',' with a plus, and then the space resulting in: "Somewhere+road++That town" ... So something like this:

<?php 
 $source=$_POST['textfield11'];
 $dest=$_POST['textfield12'];
  $time=$_POST['textfield13'];
  $only = str_replace(', ', '+', $source);
    $final = str_replace(' ', '+', $only);
  $url='http://maps.googleapis.com/maps/api/geocode/json?address=$final&sensor=false';
  $source1 = file_get_contents($url);
   $obj = json_decode($source1);
      $LATITUDE = $obj->results[0]->geometry->location->lat;
   echo $LATITUDE;
 ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM