简体   繁体   中英

Getting wrong location latitude and longitude based on address in php

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 . ', &nbsp;' . $city . ', &nbsp;' . $state. ', &nbsp;' . $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;
}

Please try replacing these lines

$address = $street . ', &nbsp;' . $city . ', &nbsp;' . $state. ', &nbsp;' . $zip; // Google HQ
$prepAddr = str_replace(' ','+',$address);

Replace

$address = $street . '+' . $city . '+' . $state. '+' . $zip; 
$prepAddr = urlencode($address);

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