I need to reverse geocode a list of thousands of latitude/longitude coordinates. I can do this for one set of coordinates no problem, but when it comes to many it will only do 5 at a time. I need to figure out how to do this in one step and time the loop so it will not get denied by google.
I have been told elsewhere that I need to utilize callback functions but I am unsure how to do this.
Here is some demo code
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="js/jquery-1.7.2.min.js" ></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var c = [];
c[0]="43.5878,-79.6777";
c[1]="49.2828,-123.1414";
c[2]="49.2895,-123.127";
c[3]="49.2784,-123.1364";
c[4]="49.0327,-122.2529";
c[5]="49.2696,-123.0587";
c[6]="49.269,-122.9954";
c[7]="49.235,-122.882";
c[8]="49.1908,-122.7508";
c[9]="49.085,-122.4111";
var a = [];
function codeLatLng(input, i) {
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng' : latlng
}, function(results, status) {
a[i] = results[0].formatted_address;
$("#test").append(a[i] + "<br />");
});
}
function showmethemoney(){
for (var i=0; i <= c.length - 1; i++) {
$("#test").append(i + ") " + c[i] + "<br/>");
codeLatLng(c[i], i);
};
}
</script>
</head>
<body>
<div id="test"></div>
<br />
<button onclick="showmethemoney();">Show me the money!</button>
</body>
I need my results to be inline with their coordinates.
Any help would be greatly appreciated!
Thanks.
Edit:
Getting a little bit further:
var geocoder = new google.maps.Geocoder();
var c = [];
c[0]="43.5878,-79.6777";
c[1]="49.2828,-123.1414";
c[2]="49.2895,-123.127";
c[3]="49.2784,-123.1364";
c[4]="49.0327,-122.2529";
c[5]="49.2696,-123.0587";
c[6]="49.269,-122.9954";
c[7]="49.235,-122.882";
c[8]="49.1908,-122.7508";
c[9]="49.085,-122.4111";
var a = [];
function codeLatLng(input, i) {
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng' : latlng
}, function(results, status) {
//$("#test").append(results[0].formatted_address + "<br />");
a[i] = results[0].formatted_address;
$("#test").append(a[i] + "<br />");
});
}
var i = 0;
function showmethemoney(start, end) {
for (i = start; i <= c.length - 1 && i < end; i++) {
$("#test").append(i + ") " + c[i] + " - ");
codeLatLng(c[i], i);
}
if( i >= c.length - 1){
return;
}
setTimeout(function(){
showmethemoney(i, i+1);
}, 1500);
}
</script>
</head>
<body>
<div id="test"></div>
<br />
<button onclick="showmethemoney(0, 1);">Show me the money!</button>
</body>
Modified function showmethemoney. by using setTimeout jsfiddle. You can change interval from 10 to any number you want.
var i = 0;
function showmethemoney(start, end ) {
for (i = start; i <= c.length - 1 && i < end; i++) {
$("#test").append(i + ") " + c[i] + "<br/>");
codeLatLng(c[i], i);
}
if( i >= c.length - 1){
return;
}
setTimeout(function(){
showmethemoney(i, i+5);
}, 10);
}
showmethemoney(i, i+5);
Related
I am having difficulty with the way google calls its maps api. I have the following calling initMap
<script defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY_REMOVED&callback=initMap">
</script>
but inside initMap, the following condition if(getPosition() !== false) { never evaluates to true because init map is done before getPosition() has set its object values.
function initMap() {
// set new map, assign default properties
map = new google.maps.Map(document.getElementById('map'), {
center: { lat, lng }, zoom: 14
});
// check if the requested data is usable (lat, lng === numbers) before trying to use it
if(getPosition() !== false) {
map.setCenter( getPosition() ); // set latest position as the map center
addMarker();
console.log("InitMap ran here");
}
}
How can I make it so initMap waits until getPosition() has had a chance to wait for other functions to do their thing? Here is my complete script so it makes more sense.
<script>
console.log(formatTime(Date()));
// https://developers.google.com/maps/documentation/javascript/geolocation
var map; var marker;
var lat = 65.025984; var lng = 25.470794; // default map location in case no position response is available
var res_data; var res_longitude; var res_latitude; var res_speed; var res_time; // res = response (data from the ajax call)
var xhr = new XMLHttpRequest();
function getPosition() {
pos = {
lat: res_latitude,
lng: res_longitude,
};
return ( isNaN(pos.lat) || isNaN(pos.lng) ) ? false : pos; // return pos only if lat and lng values are numbers
}
function initMap() {
// set new map, assign default properties
map = new google.maps.Map(document.getElementById('map'), {
center: { lat, lng }, zoom: 14
});
// check if the requested data is usable (lat, lng === numbers) before trying to use it
if(getPosition() !== false) {
map.setCenter( getPosition() ); // set latest position as the map center
addMarker();
console.log("InitMap ran here");
}
}
// place marker on the map
function addMarker() {
//console.log("Add Marker ran");
//https://developers.google.com/maps/documentation/javascript/markers
if(marker){ marker.setMap(null); } // remove visibility of current marker
marker = new google.maps.Marker({
position: getPosition(),
map: map,
title: formatTime(res_time),
});
marker.setMap(map); // set the marker
}
function getData() {
xhr.addEventListener("load", reqListener);
xhr.open("GET", "http://example.com/data.txt");
xhr.send();
}
function reqListener() {
// res_data = long, lat, accuracy, speed, time
//console.log("reqListener: " + xhr.responseText);
res_data = '[' + xhr.responseText + ']';
res_data = JSON.parse(res_data);
res_latitude = res_data[0]; res_longitude = res_data[1]; res_accuracy = res_data[2]; res_speed = res_data[3]; res_time = res_data[4];
var formatted_time = formatTime(res_time);
document.getElementById('info').innerHTML = '<span class="info">Lat: ' + res_latitude + '</span><span class="info">Long: ' + res_longitude + '</span><span class="info">Accuracy: ' + res_accuracy + '</span><span class="info">Speed: ' + res_speed + '</span><span class="info">' + formatted_time + '</span>';
addMarker();
}
function formatTime(time) {
var t = new Date(time);
var hours, mins, secs;
if(t.getHours() < 10) { hours = "0" + t.getHours(); } else { hours = t.getHours(); }
if(t.getMinutes() < 10) { mins = "0" + t.getMinutes(); } else { mins = t.getMinutes(); }
if(t.getSeconds() < 10) { secs = "0" + t.getSeconds(); } else { secs = t.getSeconds(); }
var hms = hours +':'+ mins +':'+ secs;
return 'Updated: ' + hms;
}
function init() {
getData();
setInterval(getData, 5000);
}
init();
</script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY_REMOVED&callback=initMap">
</script>
Get rid of the callback=initMap from where you load in the Maps API.
Instead make a call to initMap only from where you are then certain everything is loaded. e.g. at the end of reqListener.
function reqListener() {
res_data = '[' + xhr.responseText + ']';
res_data = JSON.parse(res_data);
res_latitude = res_data[0]; res_longitude = res_data[1]; res_accuracy = res_data[2]; res_speed = res_data[3]; res_time = res_data[4];
var formatted_time = formatTime(res_time);
document.getElementById('info').innerHTML = '<span class="info">Lat: ' + res_latitude + '</span><span class="info">Long: ' + res_longitude + '</span><span class="info">Accuracy: ' + res_accuracy + '</span><span class="info">Speed: ' + res_speed + '</span><span class="info">' + formatted_time + '</span>';
initMap();
addMarker();
}
If you're calling reqListener at repeated intervals and don't want to recreate your map, add some logic to the top of initMap like:
if (map !== null) {
return;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to execute a function that alerts an array but it doesn't work. When I press the Add button, I'm supposed to have an alert containing Lat/lng, but no alert appears.
You can see my working code here: jsfiddle. Press the Add button to see the phenomenon. I call the function f() in line 195 but I don't get anything.
My HTML code:
<div id="info"></div>
<div id="dvMap"></div>
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="wrapper">Paste coordinate data here:
<form onSubmit="javascript:return false;">
<textarea id="Coords" cols="50" rows="25"></textarea>
<div>
<input type="button" id="btnAdd" class="Button" value="Add Markers" onClick="ProcessData()">
<input type="button" id="btnClear" class="Button" value="Clear Map" onClick="Clear()">
</div>
<br>
</form>
</div>
My Javascript code:
var directionsDisplay = [];
var directionsService = [];
var map = null;
var g = [];
var path = new Array();
var routeSegment = 0;
var k = 0;
function inizialise() {
var mapOptions = {
center: new google.maps.LatLng(33.730166863, 130.7446296584),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
document.getElementById("Coords").value = '33.29702, 130.54948000000002' + '\n' + '33.29764, 130.54986000000002' + '\n' + '33.29793, 130.55010000000001' + '\n' + '33.298730000000006, 130.55066000000002' + '\n' + '33.299620000000004, 130.55129000000002'
// calcRoute() ;
}
var MyArray = [];
function Clear() {
//alert(directionsDisplay.length);
MyArray = [];
for (var i = 0; i < directionsDisplay.length; i++) {
directionsDisplay[i].setMap(null);
}
// directionsDisplay = [];
document.getElementById("Coords").value = "";
document.getElementById("Coords").disabled = false;
document.getElementById("btnAdd").disabled = false;
}
function ProcessData() {
var Points = document.getElementById("Coords").value
if (document.getElementById("Coords").value != '') {
var Points = document.getElementById("Coords").value
calcRoute(Points);
}
}
/*
function ProcessData() {
alert('ok');
if (document.getElementById("Coords").value != '') {
var Points = document.getElementById("Coords").value
AddMarkers(Points);
}
}*/
function AddMarkers(data) {
var MyData = data.substr(0, data.length);
MyArray = MyData.split("\n");
//alert(MyArray[2]);
// calcRoute();
t();
}
function calcRoute(data) {
var MyData = data.substr(0, data.length);
MyArray = MyData.split("\n");
var input_msg = MyArray;
var locations = new Array();
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < input_msg.length; i++) {
var tmp_lat_lng = input_msg[i].split(",");
//var s = new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]);
locations.push(new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]));
bounds.extend(locations[locations.length - 1]);
}
/* var mapOptions = {
// center: locations[0],
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
*/
map.fitBounds(bounds);
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
var i = locations.length;
var index = 0;
while (i != 0) {
if (i < 3) {
var tmp_locations = new Array();
for (var j = index; j < locations.length; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = 0;
index = locations.length;
}
if (i >= 3 && i <= 10) {
console.log("before :fun < 10: i value " + i + " index value" + index);
var tmp_locations = new Array();
for (var j = index; j < locations.length; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = 0;
index = locations.length;
console.log("after fun < 10: i value " + i + " index value" + index);
}
if (i >= 10) {
console.log("before :fun > 10: i value " + i + " index value" + index);
var tmp_locations = new Array();
for (var j = index; j < index + 10; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = i - 9;
index = index + 9;
console.log("after fun > 10: i value " + i + " index value" + index);
}
}
}
var coord = new Array();
function drawRouteMap(locations) {
var start, end;
var waypts = [];
for (var k = 0; k < locations.length; k++) {
if (k >= 1 && k <= locations.length - 2) {
waypts.push({
location: locations[k],
stopover: true
});
}
if (k == 0) start = locations[k];
if (k == locations.length - 1) end = locations[k];
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: false,
travelMode: google.maps.TravelMode.DRIVING
};
console.log(request);
directionsService.push(new google.maps.DirectionsService());
var instance = directionsService.length - 1;
directionsDisplay.push(new google.maps.DirectionsRenderer({
preserveViewport: true
}));
directionsDisplay[instance].setMap(map);
directionsService[instance].route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(status);
directionsDisplay[instance].setDirections(response);
var f = response.routes[0];
// var summaryPanel = document.getElementById("directions_panel");
var route = directionsDisplay[instance].getDirections().routes[0];
// var routes = response.routes;
var points = route.overview_path;
//alert(points);
var ul = document.getElementById("directions_panel");
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
// alert(nextSegment[k]);
var li = document.createElement('P');
li.innerHTML = getLatLng(nextSegment[k]);
ul.appendChild(li);
// polyline.getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
coord.push( getLatLng(nextSegment[k]));
f(coord);
}
}
}
} else {
alert("directions response " + status);
}
});
}
function f( r) {
alert(r);
}
function getLatLng(point) {
//alert(MyArray.length);
var lat = point.lat(),
lng = point.lng();
var tmp = MyArray[k].split(",");
// alert( Math.abs(parseFloat(tmp[0]- lat)) )
if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
k++;
// alert(k);
//if(k==MyArray.length) { f('animation'); }
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
} else {
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
}
}
google.maps.event.addDomListener(window, 'load', inizialise);
The problematic code is in line 195: I call f(coord), but the alert doesn't appear. I have defined the f function as such:
function f(r) {
alert(r);
}
You're overwriting f with an object in line 173:
var f = response.routes[0];
So when you try to call f, it's not a function, but an object (try logging typeof f before the call: you will get 'object').
I managed to fix the problem. I edite my function 'getLatLng()' such as :
function getLatLng(point, array) {
//alert(k);
var lat = point.lat(),
lng = point.lng();
var tmp = MyArray[k].split(",");
// alert( Math.abs(parseFloat(tmp[0]- lat)) )
if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
k++;
array.push({
"lat": lat ,
"lng": lng,
"stop":1
});
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
} else {
array.push({
"lat": lat ,
"lng": lng,
"stop":1
});
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
}
}
Now I can acess to the element of my array. Here my code
I' m having this problem , when I load my page and insert Origin and Destination, after clicking the button "locate" it doesn't show anything in the google map, because it says Response is not an object , so I tried to stamp it with console.log and it says Response=null , but if I reload the page and click fast on Locate , then it draws the route.
Here's the code
function init(){
var latlng = new google.maps.LatLng(40.635636, 17.942414);
var mapOptions = { zoom: 12, center: latlng };
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function updateMap(){
init();
var originGeocoder = new google.maps.Geocoder();
var destinationGeocoder = new google.maps.Geocoder();
var origin = document.getElementById( "origin" ).value + " Brindisi 72100";
var destination = document.getElementById( "destination" ).value + " Brindisi 72100";
var directionsService2 = new google.maps.DirectionsService();
originGeocoder.geocode( { 'address': origin }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK ) {
var startLatLng = results[0].geometry.location;
var oLat = startLatLng.lat();
var oLng = startLatLng.lng();
document.getElementById('cStart').innerHTML = oLat + " " + oLng;
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Chiamata asincrona alle API per ottenere Lat e Lng dell' indirizzo di destinazione
destinationGeocoder.geocode( { 'address': destination }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK ) {
var destLatLng = results[0].geometry.location;
var dLat = destLatLng.lat();
var dLng = destLatLng.lng();
document.getElementById('cDestination').innerHTML = typeof dLat;
document.getElementById('cDestination').innerHTML = dLat + " " + dLng;
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Salva in req[] le varie distanze tra le paline e la destinazione
singleObjToStop(origin,destination,function(paline,req,reqO){
console.log("1");
//Trova la palina più vicina alla destinazione
calcSingleDis(paline,req,reqO,function(w2,w1){
console.log("2");
//Disegna i waypoints(?)
reqEnd(origin,destination,w1,w2,function(request){
console.log("3");
directionsService2.route(request, function(response, status) {
console.log("4");
console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("distance");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + " ";
summaryPanel.innerHTML += route.legs[i].duration.text + "<br /><br />" ;
}
computeTotalDistance(response);
}
else{
console.log("ENTRA QUA STRONZO");
console.log("Fermata partenza = " + w1);
console.log("Fermata arrivo = " + w2);
}
});
directionsDisplay.setMap(map);
});
});
});
}
function singleObjToStop(origin,destination,callback){
var data=<?php echo $data; ?>;
var a,b,i=0;
var paline = new Array();
var req = new Array();
var reqO = new Array();
var num = <?php echo $n; ?>;
$.each(data, function(fieldName, fieldValue) {
a=fieldValue.geoLat;
b=fieldValue.geoLong;
a=parseFloat(a);
b=parseFloat(b);
paline[i]=new google.maps.LatLng(a,b);
req[i] = {
origin:paline[i],
destination:destination,
travelMode: google.maps.TravelMode.WALKING
};
reqO[i] = {
origin:origin,
destination:paline[i],
travelMode: google.maps.TravelMode.WALKING
};
i++;
if(i==num){
callback(paline,req,reqO);
}
});
}
function calcSingleDis(paline, req, reqO, callback) {
var directionsService = new google.maps.DirectionsService();
var c = 10000000;
var w2 = new google.maps.LatLng(0, 0);
var w1 = new google.maps.LatLng(0, 0);
var num = <?php echo $n; ?>;
var j = (num - 1);
var t;
var cO = 10000000;
var numO = <?php echo $n; ?>;
var jO = 0;
for (j = 0; j < num; j++) {
t = 0;
directionsService.route(req[j], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//directionsDisplay.setDirections(response);
var troute = response.routes[0];
var dis = parseFloat((troute.legs[0].distance.text).replace(",", "."));
document.getElementById('test').innerHTML = dis;
//se distanza minore di quella minore trovata fin ora la cambia
if (dis < c) {
w2 = paline[j - num];
c = dis;
}
if (t == (num - 1)) {
console.log("QUA ENTRA LOL");
for (jO = 0; jO < numO; jO++) {
console.log("E NON ENTRA MANNAC");
t = 0;
directionsService.route(reqO[jO], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log("E NON ENTRA MANNAC22222");
//directionsDisplay.setDirections(response);
var troute = response.routes[0];
var disO = parseFloat((troute.legs[0].distance.text).replace(",", "."));
document.getElementById('test').innerHTML = dis;
//se distanza minore di quella minore trovata fin ora la cambia
if (disO < cO) {
w1 = paline[jO - numO];
cO = disO;
}
if (t == (numO - 1)) {
console.log("W1 = " + w1);
console.log(response);
callback(w2, w1);
}
}
jO++;
t++;
});
}
}
}
j++;
t++;
});
}
}
function reqEnd(origin,destination,w1,w2,callback){
var request = {
origin:origin,
destination:destination,
waypoints: [{location: w1} , {location: w2}],
//waypoints: [{location: w2}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
callback(request);
}
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: "+ totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
google.maps.event.addDomListener( window, 'load', init );
The problem is related to the limit of query that you can use with Google Maps API v3.
You can take a look here: https://developers.google.com/maps/documentation/business/faq#google_maps_api_services
You probably do lots of requests to the API with your program, while you have quite restrictive limits as you can see from google Q&A.
Applications should throttle requests to avoid exceeding usage limits,
bearing in mind these apply to each client ID regardless of how many
IP addresses the requests are sent from.
You can throttle requests by putting them through a queue that keeps
track of when are requests sent. With a rate limit or 10 QPS (queries
per second), on sending the 11th request your application should check
the timestamp of the first request and wait until 1 second has passed.
The same should be applied to daily limits.
Even if throttling is implemented correctly applications should watch
out for responses with status code OVER_QUERY_LIMIT. If such response
is received, use the pause-and-retry mechanism explained in the Usage
limits exceeded section above to detect which limit has been exceeded.
You could find useful: How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?
The Google Maps API provides a geocoder class for geocoding and reverse geocoding dynamically from user input. read more check Geolocation demo here and more HTML5 Geolocation to check here
I've been trying to convert a v2 to v3 map application that calculates the distance between and address entered and a stored lat/Lon. Not having any luck with getting this up and running. Would really appreciate some help.
<script type="text/javascript" src="js/addHTMLControls2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#order").validate();
addInput();
});
</script>
<script type="text/javascript">
var geocoder, location1, location2;
function initialize() {
geocoder = new google.maps.Geocoder();
}
function showLocation() {
document.getElementById('address').value= document.getElementById('address2').value;
/*coordinate system*/
geocoder.geocode(document.forms[0].address1.value,
function (response) {
if (!response || response.Status.code != 200)
{alert("Sorry, we were unable to geocode the first address");}
else
{location1 =
{lat: response.Placemark[0].Point.coordinates[1],
lon: response.Placemark[0].Point.coordinates[0],
address: response.Placemark[0].address
};
geocoder.geocode(document.forms[0].address2.value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
calculateDistance();
}
});
}
});
}
function calculateDistance()
{
try
{
var map;
var directionsPanel;
var directions;
var glatlng1 = new google.maps.LatLng(location1.lat, location1.lon);
var glatlng2 = new google.maps.LatLng(location2.lat, location2.lon);
var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
var kmdistance = (miledistance * 1.609344).toFixed(1);
map = new google.maps.Map(document.getElementById("map_canvas"));
map.setCenter(new google.maps.LatLng(location1.lat, location1.lon), 15);
directionsPanel = document.getElementById("route");
directions = new GDirections(map, directionsPanel);
document.getElementById('route').innerHTML='';
document.getElementById('map_canvas').innerHTML='';
/* location1.address+ */
//alert(document.getElementById('hdnLat').value);
document.getElementById('distance').value = directions.load("from:"+ document.getElementById('hdnLat').value +"," + document.getElementById('hdnLan').value + " to: "+location2.address, {travelMode:G_TRAVEL_MODE_DRIVING});
/* document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';*/
setTimeout('adjustdistance(document.getElementById("route").innerHTML)', 8000);
;
document.getElementById('distance').value= 'calculating...';
}
catch (error)
{
alert(error);
}
}
function adjustdistance(htmlcode)
{
var ht1;
ht1 = htmlcode;
var tyu;
tyu= parseReturnedXML(ht1,'$Route.summaryHtml','table jstcache');
document.getElementById('distance').value=tyu;
}
function parseReturnedXML(strToParse, strStart, strFinish)
{
var str;
str=strToParse;
var str1;
var str2;
str = str.replace(strStart,'~');
str = str.replace(strFinish,'~');
str=str.replace(/(<([^>]+)>)/ig,"");
str = str.replace(',','');
str = str.replace(' ','');
str1= str.indexOf('km (');
str2=" km(s)";
if(str1=='-1')
{
str1=str.indexOf('mi (');
str2=" miles";
}
var str4;
var str5;
str4 = parseInt(str1) - 8;
str5 = parseInt(str1) + 2;
str = str.substring(str4,str5);
str = str.replace(/[a-zA-Z]/g,"");
str = str.replace(/^\s+/,"");
str = str+str2;
return str;
}
</script>
I've updated the various v3 changes but its simply not returning a distance for me.
Thanks
Alan
Please refer the link. http://jsfiddle.net/xJ26V/1/
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
I'm using a Google Maps plugin, and I want it to show up on the page load as well as all postbacks. It seems to only work on postbacks though. Any ideas? I have the body onload tag as "body background="#ccccff" onload="initialize()"", but the function is not defined the first time. Why? Here is the code:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
var mostRecentInfo;
function initialize() {
var center = new google.maps.LatLng(0, 0);
var mapOptions = {
center: center,
zoom:1,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var posStr = <%=JSON%>;
if (posStr.toString() != "0") {
var test = posStr.toString().split(',');
var groundstation = <%=groundStation%>;
var dateTimeStr = <%=datetimesStr%>;
var AUStr = <%=auStr%>;
var spaceCraft = <%=spacecraft%>;
var dateTimes = dateTimeStr.toString().split(',');
var auIDs = AUStr.toString().split(',');
var latitude = new Array((test.length / 2));
var longitude = new Array(latitude.length);
var i = 0;
var markerArray = new Array();
for (var j = 0; j < (test.length - 1); j = j + 2) {
latitude[i] = eval(test[j+1]);
longitude[i] = eval(test[j]);
var position = new google.maps.LatLng(latitude[i], longitude[i]);
var marker = new google.maps.Marker({
map:map,
position:position
});
markerArray.push(marker);
i++;
}
var sumLat = 0;
var sumLong = 0;
for (i = 0; i < latitude.length; i++) {
sumLat += latitude[i];
sumLong += longitude[i];
}
var avgLat = sumLat / latitude.length;
var avgLong = sumLong / longitude.length;
center = new google.maps.LatLng(avgLat, avgLong);
map.panTo(center);
var circle;
var contentStr = new Array();
for (i = 0; i < markerArray.length; i++) {
position = markerArray[i].getPosition();
var circOptions = {
strokeColor:"#770000",
strokeOpacity:0.1,
fillColor:"#881111",
fillOpacity:0.4,
map:map,
center:position,
radius:2500000
};
circle = new google.maps.Circle(circOptions);
marker = markerArray[i];
contentStr[i] = '<div id="content">' +
'<b>Spacecraft: </b>' + spaceCraft.toString() + '<br />' +
'<b>Start Time (UTC): </b>' + dateTimes[i].toString() + '<br />' +
'<b>Position: </b>(' + latitude[i].toString() + ', ' + longitude[i].toString() + ')<br />' +
'<b>AU ID: </b>' + auIDs[i] + '<br />' +
'<b>Downlink Station: </b>' + groundstation.toString() + '<br />' +
'</div>';
addListener(map, marker, contentStr[i]);
}
}
}
function addListener(map, marker, content) {
var infowindow = new google.maps.InfoWindow({
content:content
});
google.maps.event.addListener(marker, 'mouseover', function() {
if (mostRecentInfo)
mostRecentInfo.close();
mostRecentInfo = infowindow;
infowindow.open(map, this);
});
}
etc.
It is likely a timing issue with the onload function being called before the initialize function is ready. This is the reason libraries like jQuery have a document.ready function. You can try removing the onload and place a call to initialize() at the bottom of your HTML, just prior to the closing body tag. This will probably work for you.
If you have the option, I'd use a library so you can assure that the function is there and your page is ready. If you haven't tried it, give jQuery a shot.