Reputation: 3
I got the following piece of code, but it doesn't seem to get the right values for lat and long. It gives me 0,000000 in return. When I check an adress, it gives me the right values in the json.
mysql_select_db($dbname);
$result = mysql_query("SELECT id, street, postalcode, place, lat, lng FROM stores") or die(mysql_error());
while($row = mysql_fetch_array( $result )){
$addressbar = $row['street']." ".$row['postalcode']." ".$row['place'];
$address = urlencode($addressbar);
$json = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=true");
$decoded = json_decode($json);
$lat = $decoded->results[0]->geometry->location->lat;
$lng = $decoded->results[0]->geometry->location->lng;
mysql_query("UPDATE stores SET lat='$lat', lng='$lng' WHERE id=".$row['id']."") or die(mysql_error());
printf( $addressbar."%d\n", mysql_affected_rows());
echo "<br/><br/>";
}
I can't seem to find what I'm doing wrong. I hope anyone can help me out.
Upvotes: 0
Views: 979
Reputation: 57398
The Google querying code and the JSON decoding are correct; I tried them myself and, if the address checks (the one I tried did), it correctly issues lat and lng.
Try printing the query and inspecting executing it manually from client.
The only possibilities that came to me are:
Other possibilities which did not come to me:
I also vote for Allen Holman's advice.
Upvotes: 1
Reputation: 125
A few things! To debug, I would do the following:
I would print out $json, if you are getting 0's back from the map api, you may be able to see an error msg back in the $json text. If you are getting lat/lng in $json, then add more debugging to your mysql query or print out the query before it goes to the exec function. For example to add more debugging:
DBI->connect( $dsn, $username, $password, { 'PrintError' => 1 } )
If it is not in $json, then I would manually go to the map api URL to see what I get back
I'm sure you trust the data back from google, but please get in the habit of using placeholders when doing any query. Placeholders (?) instead of putting the variables directly in the SQL code protect you from SQL injection. Ex:
$mysqlquery = $dbh->prepare( 'UPDATE stores SET lat=?, lng=? WHERE id=?' );
$mysqlquery->execute( $lat, $lng, $row['id'] );
Sometimes it helps me when I am debugging to print out what I am about to send to an API. Instead of sending the URL or query directly to the function, put it in a variable, print that variable out, then send the variable to the function/api. You may be assuming that it is correct, but some small issue is preventing it from working that is obvious if you see the string.
Hope this all helps a bit, good luck!
Upvotes: 2