Reputation: 790
Finding the location latitude and longitude based on street, city, state, zip using Google map. I'm taking the address from Google map and trying to find latitude and longitude. But my code always gives wrong place location.
Code:-
<?php
$con = mysql_connect("localhost","location","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$street =$_REQUEST[street];
$city =$_REQUEST[city];
$state =$_REQUEST[state];
$zip =$_REQUEST[zip];
$result=null;
mysql_select_db("map", $con);
$address = $street . ', ' . $city . ', ' . $state. ', ' . $zip; // Google HQ
$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;
if($lat==0.0000 && $long==0.0000){
$result="ERROR";
}else{
$sql="INSERT INTO markers (name, address, lat, lng) VALUES ('".$street."', '".$city.", " .$state ."', '".$lat."', '".$long."')";
$result="SUCCESS";
}
if (!mysql_query($sql,$con)) {
echo $result;
} else {
echo $result;
}
Upvotes: 1
Views: 1384
Reputation: 101
Please try replacing these lines
$address = $street . ', ' . $city . ', ' . $state. ', ' . $zip; // Google HQ
$prepAddr = str_replace(' ','+',$address);
Replace
$address = $street . '+' . $city . '+' . $state. '+' . $zip;
$prepAddr = urlencode($address);
Upvotes: 1