将变量从javascript传递到php以获取地理定位功能

时间:2018-05-04 07:57:14

标签: javascript php html

嘿伙计我想从javascript代码中获取经度和纬度将其传递给php变量$ lat和$ lng所以我可以获得$ city并在我的sql查询中使用它(查询不包括在内)。以下是我的代码。请帮忙

        <html>

<head>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        document.write("Geolocation is not supported by this browser.");
    }
}
function showPosition(position) {

  var latitude= position.coords.latitude;
  var longitude= position.coords.longitude); 

}
</script>
</head>
<body onload="getLocation()"></body>
</html>
<?php

 function getaddress($lat,$lng)
  {
     $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
     $json = @file_get_contents($url);
     $data=json_decode($json);
     $status = $data->status;
     if($status=="OK")
     {
       return $data->results[0]->formatted_address;
     }
     else
     {
       return false;
     }
  }
   $lat= 33.568711799999996; //latitude
  $lng= 35.3800354; //longitude
  $address= getaddress($lat,$lng);
  if($address)
  {
    // Delimiters may be slash, or comma
    //$date = "04/30/1973";
    list($address, $street, $city) = split('[,-]', $address);
    echo "Address: $address; Street: $street; City: $city <br />\n";

  }
  else
  {
    echo "Not found";
  }
?>

1 个答案:

答案 0 :(得分:1)

您应该将PHP脚本移动到另一个文件,例如script.php而不是jquery get

$.get( "script.php", { lat: "123", lon: "321" }, function( data ) {
    alert( data ); // or you can insert result text to your block
});

用这个开始你的PHP脚本:

if(isset($_GET['lat']) && isset($_GET['lon']))

P.S。不要忘记包含jquery lib