2013-08-25 25 views
7

我有這樣的代碼,如何獲取通過輸入框輸入的城市/國家的經度和緯度?

<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
function myIP(){ 
$("#btn").click(function(){ 
      var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': '#city'}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
      alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng()); 
      } else { 
      alert("Something got wrong " + status); 
      } 
     }); 
}); 
} 
</script> 
</head> 
<body onload="myIP()"> 
<input type="text" id= "city"> 
<input id="btn" type="button" value="get Lat&Long" /> 
</body> 
</html> 

這會給我的緯度和小對話框中輸入城市的經度。但我需要在同一頁面或父頁面。請幫我

+0

這是你自己的代碼?在這種情況下,你有什麼嘗試? –

+0

不是我的代碼。我試圖通過php輸入表單徒勞地輸入它。 – phpbeg

+0

當我嘗試使用這個時,無論我輸入什麼,我都得到相同的座標。 –

回答

5
<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
function myIP(){ 
$("#btn").click(function(){ 

      var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': $('#city').val()}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
      $('.push-down').text("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng()); 
      } else { 
      $('.push-down').text("Something got wrong " + status); 
      } 
     }); 
}); 
} 
</script> 
    <style> 
    .push-down {margin-top: 25px;}</style> 
</head> 
<body onload="myIP()"> 
<input type="text" id= "city"> 
<input id="btn" type="button" value="get Lat&Long" /> 
    <div class="push-down"></div> 
</body> 
</html> 
+0

但是,該代碼仍然不適用於我。是否有任何我需要從我的結尾添加。 – phpbeg

+0

你是什麼意思「不工作」?有沒有什麼錯誤?你的瀏覽器的控制檯說什麼? – alkis

+0

我非常抱歉,從我的結尾是一個錯誤。它完美的工作。但你能幫我在頁面而不是在對話框彈出框中獲得結果。 – phpbeg

0
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + Loc + '&sensor=false', null, function (data) { 
       var p = data.results[0].geometry.location 
       var latlng = new google.maps.LatLng(p.lat, p.lng);      
      }); 
相關問題