如何通过输入框获取输入的城市/国家的经纬度?

8

我有这段代码:

<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>

这将在一个小的对话框中给出输入城市的纬度和经度。但我需要在同一页或父页面上展示。请帮助我。

这是你自己的代码吗?如果是,你尝试过什么? - Andy G
不是我的代码。我尝试通过 PHP 输入表单输入它,但失败了。 - phpbeg
当我尝试使用它时,无论我输入什么,我都会得到相同的坐标。 - Jeremy Johnson
1
geocoder.geocode( { 'address': '#city'} . 你把 #city 放在了应该放输入的地方,输入应该是 $('#city').val()。 - Alkis Kalogeris
它不起作用。 - phpbeg
显示剩余3条评论
2个回答

6
<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>

但是那段代码对我仍然不起作用。我需要从我的端口添加任何东西吗? - phpbeg
你说的“不工作”是什么意思?有出现任何错误吗?你的浏览器控制台显示了什么? - Alkis Kalogeris
非常抱歉,那是我的错误。它现在已经完美运作了。但是你能帮我将结果显示在页面上而不是在弹出对话框中吗? - phpbeg
我更新了代码,将消息显示在输入框下方一点。你说“页面”,所以我选择了同一页。如果这解决了你的问题,请不要忘记接受答案。 - Alkis Kalogeris
当然,我会接受的。非常感谢你,Alkis。它完美地运行了。 - phpbeg
显示剩余2条评论

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);                    
            });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接