2014-03-18 286 views
0

我想将地址转换成latitude.here是我的代码。 但它给错了纬度。如果我手动将地址放在$最后的地方,它会给出正确的纬度。但是我无法对其进行硬编码,无论源文本框中有什么来源,我都必须找出地址纬度。什么是错误?php地址转为经纬度

<?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; 
?> 
+0

也许你已经尝试了一些什么信息? http://blog.codinghorror.com/rubber-duck-problem-solving/ – Smandoli

+0

我的猜测是你给'$ final'的价值正在被搞砸。你是否在geocode调用之前尝试了var_dump($ final)来查看'$ final'实际上是什么? – Rottingham

+0

如果$ final包含不安全的URL字符,那可能会将其搞乱(除了将空格改为加号)。可以试试$ final = urlencode(仅限$); – SyntaxLAMP

回答

-1

,后的str_replace此刻添加一个空格...... COS,如果用户键入一个地址为“在某处公路,那个小镇”将取代“”有加,并那么造成的空间:“在某处公路+ ++那个小镇” ......因此,像这样:

<?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; 
?> 
1

而不是使用str_replace的,你应该使用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; 
?> 
0
<? 
$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; 
?> 
+0

thnxx.urlencode by xml is working.but still its not given precise latitude,longitude value,which geocode shows.e.g let let纬度是31.5140,尽管这段代码给出了31.4542。现在该怎么办? – user3140387

+0

确保$ source中的地址具有足够的特定范围,以缩小到某个地区,例如邮政编码和国家/地区。在谷歌地图上查找坐标,看看街道名称与来源相比是否相关 –