问题描述:

I am trying to get the Latitude & Longitude of a point from its address.

Everything is working fine when I work with only one point but things become ugly when I use this in a loop and try to use it for multiple points.

My code looks like this:

<?php

$con = mysql_connect("localhost", "root", "");

mysql_select_db("ppialakm_db", $con);

function get_latlong($address){

$prepAddr = str_replace(' ','+',$address);

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

$output= json_decode($geocode);

$lat = $output->results[0]->geometry->location->lat;

$long = $output->results[0]->geometry->location->lng;

return array("latitude"=> $lat, "longitude"=> $long);

}

$queryyyy = mysql_query("SELECT broker_property_id, sector, locality, city FROM property_requirement");

while($array = mysql_fetch_assoc($queryyyy)){

$address = $array['sector'].",".$array['locality'].",".$array['city'].",Maharashtra";

$ahfaho = get_latlong($address);

$latlong = "POINT(".$ahfaho['latitude']." ".$ahfaho['longitude'].")";

$query = mysql_query("UPDATE property_requirement SET latlong=GeomFromText('".$latlong."') WHERE broker_property_id='".$array['broker_property_id']."'");

//echo $array['broker_property_id'].'<br/>';

}

echo "Success."

?>

The problem is that many of the latlong fields remain to be empty and that too in a random order after I run this script.

I am unable to get the problem. Can anyone help me out? I am using MySQL 5.5

网友答案:

It may help to validate what you're getting back from the geocode:

function get_latlong($address){
        $prepAddr = str_replace(' ','+',$address);

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

        $output= json_decode($geocode);

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

            return array("latitude"=> $lat, "longitude"=> $long);
        }
        else { return false; }
    }

And:

if ( $ahfaho = get_latlong($address) ) {
    $latlong = "POINT(".$ahfaho['latitude']." ".$ahfaho['longitude'].")";

    $query = mysql_query("UPDATE property_requirement SET latlong=GeomFromText('".$latlong."') WHERE broker_property_id='".$array['broker_property_id']."'");
}
else { echo "Failed geocode."; }
相关阅读:
Top