地理位置:用经纬度填充表格。 Google Maps API [英] Geolocation: Filling forms with latitude and longitude. Google Maps API

查看:174
本文介绍了地理位置:用经纬度填充表格。 Google Maps API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在建立一个谷歌地图,用户在表单中分享信息和他们当前的位置。我想用Geolocation函数自动填充表单中的lat,lng字段。我唯一不能做的就是最后一步。以下是我的代码:

I've been building a google map where users share information plus their current location in a form. I want to automatically fill the lat, lng fields in my form with the Geolocation function. The only thing I cannot do is that last step. Here is my code:

<script src="https://maps.googleapis.com/maps/api/js?V=3.exp&key=wootwootwootwoot"></script>

    <script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>

var map;

function initialize() {
var mapOptions = {
zoom: 12
};
map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);

if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
  var pos = new google.maps.LatLng(position.coords.latitude,
                                   position.coords.longitude);

  var marker = new google.maps.Marker({
    map: map,
    position: pos,
    title: 'GPS'
  });

  map.setCenter(pos);
}, function() {
  handleNoGeolocation(true);
});
} else {

handleNoGeolocation(false);
}
}

function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}

var options = {
map: map,
position: new google.maps.LatLng(19.043516, -98.198232),
content: content
};

var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);


google.maps.event.addListener(marker, 'GPS', function() {
                var lat = marker.getPosition().lat();
                var lng = marker.getPosition().lng();
                $('#lat').val(lat);
                $('#lng').val(lng);
            });

}

google.maps.event.addDomListener(window, 'load', initialize);

</script>
</head>
<body>
<div id="map-canvas"></div>

    <input id="lat"/>
    <input id="lng"/>

</body>
</html>


推荐答案

您可以尝试下面的代码:

You can try this code instead :

navigator.geolocation.getCurrentPosition(function(position) {

  var pos = new google.maps.LatLng(position.coords.latitude,
                                   position.coords.longitude);
  document.getElementById('lat').value = position.coords.latitude;
  document.getElementById('lng').value = position.coords.longitude;    
  var marker = new google.maps.Marker({
    map: map,
    position: pos,
    title: 'GPS'
  });

  map.setCenter(pos);
}, function() {
  handleNoGeolocation(true);
});

最好把你的javascript代码放在< / body> 标记

it's better to put your javascript code before the </body> tag

这篇关于地理位置:用经纬度填充表格。 Google Maps API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆