2016-12-29 33 views
0

两个不同的部分(获取位置和获取餐厅)在单独执行时运行速度很快,但是如果放在一起需要几秒钟才能加载数据。 为了简化,我想获取最近的城市,以便在接收来自php的数据时将其用作变量。 任何想法可能是错误的?使用jquery获取位置,将位置变量传递给php,太慢解决方案

//get location, returns city 
navigator.geolocation.getCurrentPosition(success, error); 
function success(position) { 
    var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' 
     + position.coords.latitude 
     + '%2C' 
     + position.coords.longitude 
     + '&language=sv'; 
    $.getJSON(GEOCODING).done(function (location) { 
     $("#searchField").val(location.results[0].address_components[4].long_name); 
     getrestaurant(); 
    }) 
} 
function error(err) { 
    console.log(err) 
} 

//get nearby restaurants, returns html-code 
function getrestaurant() { 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      document.getElementById("restaurantDetails").innerHTML = 
        this.responseText; 
     } 
    }; 
    xmlhttp.open("GET", "restaurantload.php?search=" + 
      $("#searchField").val(), true); 
    xmlhttp.send(); 
} 

回答

0

努力在后端侧搜索字段值, 发送lat和液化天然气restaurantload.php?

$ch = curl_init('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$lng.'&sensor=false'); 
curl_setopt($ch, CURLOPT_POST, false); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$response = json_decode(curl_exec($ch)); 
$response = (array)$response; 

$resp = isset($response['results']) ? (array)$response['results'] : []; 
$resp = isset($resp[0]) ? (array)$resp[0] : []; 
$resp = isset($resp['address_components']) ? (array)$resp['address_components'] : []; 
+0

谢谢你的回答!我会尝试你的解决方案,但我宁愿使用前端,因为缺乏后端电源。 – user3415034