请参阅下面的代码,我是 javascript 的业余爱好者,如果真的很糟糕,我很抱歉。基本上,我的功能在获得并通过某些表格和其他功能someFunc()
后,按下按钮即可激活。我认为这是一个错误,我认为这必须是一个相当简单的修复,我刚刚有了一个线索。eventlocation
currentlocation
NaN
这两个全局变量globalevent
并globalcurrent
使用文档中的设置值回显正确的坐标,someFunc()
但计算距离不起作用。当我“发布”坐标并将它们作为 php 变量返回时,它计算得很好。
更新:以下作品 @geocodezip 让我朝着正确的方向前进。
var map;
var pos;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function getLocation(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
document.getElementById('distance').value = pos;
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
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(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function createLine()
{
geocoder = new google.maps.Geocoder();
var address = document.getElementById('distance').value;
var address2 = document.getElementById('address').value;
var temp, temp2;
geocoder.geocode({ 'address': address }, function (results, status) {
temp = results[0].geometry.location;
geocoder.geocode({ 'address': address2 }, function (results, status) {
temp2 = results[0].geometry.location;
var route = [
temp,
temp2
];
var polyline = new google.maps.Polyline({
path: route,
strokeColor: "#ff0000",
strokeOpacity: 0.6,
strokeWeight: 5
});
var lengthInMeters = google.maps.geometry.spherical.computeLength(polyline.getPath());
var distance = lengthInMeters/1000*0.621371192;
document.getElementById('distance2').value = distance;
polyline.setMap(map);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);