See the code below, I am amateur at javascript so sorry if it is really bad.
Basically my function someFunc()
is activated upon the press of a button after it has got the eventlocation
and the currentlocation
through some of forms and the other functions.
I assume NaN
is an error and I reckon that this has to be a fairly simple fix, I just done have a clue.
The two global variables globalevent
and globalcurrent
echo the correct coordinates using the doc set value in the someFunc()
but the calculate distance isn't working. When I 'POST' the coords and bring them back as php variables it calculates just fine.
UPDATE: The following works @geocodezip put me in the right direction.
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);