Google maps api v2 to v3 - javascript

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

Related

How do I get multiple elevations using google api?

I'm trying to get multiple elevations using Google API, but it usually it does not work.
Here is my code:
var axios = require('axios');
var fs = require('fs');
const util = require('util');
var config = {
method: 'get',
url: 'https://maps.googleapis.com/maps/api/elevation/json?key=<MY_API_KEY>&locations=',
headers: { }
};
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getElevationsWithAPI(config) {
console.log('in getElevationsWithAPI()');
console.log(config);
console.log('method = ' + config.method);
let queryResult = [];
let res = await axios(config); // comment 1
console.log('status = ' + res.status);
console.log('location = ' + res.data.results[0].location.lat + ', ' + res.data.results[0].location.lng);
console.log('elevation = ' + res.data.results[0].elevation);
let results = res.data.results;
for (i = 0; i < results.length; i++) {
let entry = results[i];
queryResult.push({[entry.location.lat + ',' + entry.location.lng]: entry.elevation});
}
const json = JSON.stringify(queryResult);
//console.log('json = ' + json);
return queryResult;
}
function getDistance(lat1, lng1, lat2, lng2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lng2-lng1);
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;
}
function deg2rad(deg) {
return deg * (Math.PI/180);
}
async function getElevationsExported(fileName, lat1, lng1, lat2, lng2) {
console.log('in getElevationsExported(), fileName = ' + fileName);
console.log(`lat1 = ${lat1}, lat2 = ${lat2}, lng1 = ${lng1}, lng2 = ${lng2}`);
console.log('lat distance: ' + getDistance(lat1, lng1, lat2, lng1));
console.log('lng distance: ' + getDistance(lat1, lng1, lat1, lng2));
console.log('point distance: ' + getDistance(lat1, lng1, lat2, lng2));
var url = config.url;
var res = [];
let counter = 0;
console.log('before for');
try {
// Calculate number of rows
for (i = lat1; i <= lat2 + 0.00026; i += 0.00026) {
counter++;
}
console.log('counter = ' + counter);
// Send the location data to google elevation API
let k = 1;
for (i = lat1; i <= lat2 + 0.00026; i += 0.00026) {
console.log(`${k++}: i = ${i}`);
var locations = '';
let jArr = [];
for (j = lng1; j <= lng2; j += 0.00032) {
jArr.push(j);
locations += i.toFixed(5) + '%2C' + j.toFixed(5) + '%7C';
}
locations = locations.slice(0, -3); // remove the last %7C character
config.url = url + locations;
//console.log('config.url = ' + config.url);
try {
await sleep(10); // comment 2
var elevationRes = getElevationsWithAPI(config);
elevationRes.then(function(result) {
//console.log(result);
counter--;
res.push(...result);
console.log('after --, counter = ' + counter);
if (counter === 0) { // comment 3
console.log('finished getting data');
// Write the new elevations file
fs.writeFile(consts.ElevationDirFullPath + fileName, JSON.stringify(res), (err) => {
if (err) {
console.log(err);
throw err;
}
console.log('The file has been saved');
});
}
});
} catch(error) {
console.log(error);
throw error;
}
}
console.log('exited for loop');
} catch (error2) {
console.log('error2 = ' + error2);
}
}
module.exports.getDistance = getDistance;
module.exports.getElevationsExported = getElevationsExported;
The problem is when I call Google API through axios (see comment 1). Sometimes it succeeds and sometimes it fails. I also tried to add timeout between calls (see comment 2), but then not all calls to getElevationsWithAPI() are called.
Also I usually don't reach the end condition (comment 3).
How can I fix all these problems?

i can't show span in function - javascript

i don't know how i can used if inside function then show it by span in html.
this my function:
<script type="text/javascript" src="praytimes.js"></script>
<script type="text/javascript">
function ptt() {
var date = new Date(); // today
var dhours = new Date().toTimeString().split(" ")[0];
var PT = new PrayTimes('Makkah');
var times = PT.getTimes(date, [24.46666, 39.59998], +3);
if (times.fajr > dhours){
document.getElementById("pyr").innerHTML = '<center>الفجر <br/>'+ times.fajr + '</center>';
} else if (times.sunrise > dhours){
document.getElementById("pyr").innerHTML = '<center>الإشراق <br/>'+ times.sunrise + '</center>';
} else if (times.dhuhr > dhours){
document.getElementById("pyr").innerHTML = '<center>الظهر <br/>'+ times.dhuhr + '</center>';
} else if (times.asr > dhours){
document.getElementById("pyr").innerHTML = '<center>العصر <br/>'+ times.asr + '</center>';
} else if (times.maghrib > dhours){
document.getElementById("pyr").innerHTML = '<center>المغرب <br/>'+ times.maghrib + '</center>';
} else if (times.isha > dhours){
document.getElementById('pyr').innerHTML+='<center>العشاء <br/>'+ times.isha + '</center>';
} else if (times.midnight > dhours){
//document.write('<br/>العشاء = '+ times.midnight);
document.getElementById('pyr').innerHTML+='<center>منتصف الليل '+ times.midnight + '</center>';
}
}
setTimeout('ptt()',1000);
</script>
and this tag in html:
<span id='pyr'></span>
but i can't show the result in html.
You can access a specific HTML element using the getElementById() method.
In your case the span's ID is pyr:
document.getElementById("pyr");
Now simply replace document.write() by document.getElementById("pyr").innerHTML+="your content here";
For example:
document.write('<br/>fa = '+ times.fajr);
becomes
document.getElementById("pyr").innerHTML+="<br/>fa = "+ times.fajr;
I don't think you call the function, at least not in the code you provided. Try to give your function a name and then call it.
function funcName () { ... }
funcname()
please i added new code to read lat and lng from gps:
navigator.geolocation.getCurrentPosition(function (pos) {
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
if (lat == null) {
var lat = 24.46666;
var lng = 39.59998;
} else {
alert("Latitude: "+ lat + " , Longitude: " + lng );
}
});
var date = new Date(); // today
var dhours = new Date().toTimeString().split(" ")[0];
var PT = new PrayTimes('Makkah');
var times = PT.getTimes(date, [lat, lng], +3);
but this line:
var times = PT.getTimes(date, [lat, lng], +3);
can't read lat and lng from this lines:
if (lat == null) {
var lat = 24.46666;
var lng = 39.59998;
please what is the wronge?

the google map api doesn't works

the current location as well as the distance from a given coordinate is displayed as per the expectation but a location (given in coordinates) is not being displayed on the google maps on the web page. i have included the google maps api and the console doesn't shows any error. been banging my head for quite a while to solve the issue. any help would be highly appreciated.
window.onload = getMyLocation ;
var ourCoords = {
latitude: 47.624851,
longitude: -122.52099
};
function getMyLocation () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation , displayError);
}
else {
alert("opps! no geolocation support.");
}
}
function displayError (error) {
var errorTypes = {
0: "Unknown Error",
1: "Permission Denied",
2: "location is not available",
3: "Request timed out!"
};
var errorMessage = errorTypes[error.code];
if (error.code == 0 || error.code == 2) {
errorMessage = errorMessage + " " + error.Message ;
}
var div = document.getElementById("accurateLocation");
div.innerHTML = errorMessage ;
}
function computeDistance(startCoords , destCoords){
var startLatRads = degreesToRadians (startCoords.latitude);
var startLongRads = degreesToRadians (startCoords.longitude);
var destLatRads = degreesToRadians (destCoords.latitude);
var destLongRads = degreesToRadians (destCoords.longitude);
var Radius = 6371 ;
var distance = Math.acos(Math.sin(startLatRads) * Math.sin(destLatRads) +
Math.cos(startLatRads) * Math.cos(destLatRads) *
Math.cos(startLongRads - destLongRads)) * Radius;
return distance ;
}
function degreesToRadians (degrees) {
var radians = (degrees * Math.PI) / 180 ;
return radians;
}
function displayLocation (position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
var div = document.getElementById("accurateLocation");
div.innerHTML = "your latitude is: " + latitude + " and your longitude is :" + longitude ;
var km = computeDistance(position.coords , ourCoords) ;
var distance = document.getElementById("distance") ;
distance.innerHTML = " You are " + km + " km away from the headquarter" ;
showMap(position.coords);
}
var map ;
function showMap(coords){
var googleLatAndLong = new google.maps.LatLng (coords.latitude , coords.longitude);
var mapOptions = {
zoom: 10 ,
center: googleLatAndLong,
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map (mapDiv , mapOptions);
}
<body>
<center>
<h2 id ="accurateLocation" ></h2>
<div id="distance"></div>
<div id="map"></div>
</center>
</body>

Uncaught TypeError: Cannot read property '0' of undefined - OpenWeatherMap API

I keep getting this Uncaught TypeError: Cannot read property '0' of undefined
The code works perfectly fine with no errors in the console or anything, but everything now and then this error pops up then just disappears. Does anyone know why?
var temp, loc, icon, hum, wind, dir;
var APPID = "56a4fe4f1240df2a9fe267b687a5d191";
function update (weather) {
temp.innerHTML += weather.temp;
loc.innerHTML += weather.loc;
hum.innerHTML += weather.hum;
wind.innerHTML += weather.wind;
dir.innerHTML += weather.dir;
sUp.innerHTML += weather.sUp;
sDown.innerHTML += weather.sDown
icon.src = "//openweathermap.org/img/w/" + weather.icon + ".png";
}
window.onload = function () {
temp = document.getElementById ("t");
loc = document.getElementById ("l");
icon = document.getElementById ("i");
hum = document.getElementById ("h");
wind = document.getElementById ("w");
dir = document.getElementById ("d");
sUp = document.getElementById ("sU");
sDown = document.getElementById ("sD");
if (navigator.geolocation) {
var showPos = function (pos) {
updateLoc (pos.coords.latitude, pos.coords.longitude);
}
navigator.geolocation.getCurrentPosition (showPos);
} else {
var zip = window.prompt("Your location could not be found, please enter your post/zip code.");
updateByZip(zip);
}
}
function updateLoc (lat, long) {
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"lat=" + lat +
"&lon=" + long +
"&APPID=" + APPID;
sendRequest (url);
}
function updateByZip(zip){
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"zip=" + zip +
"&APPID=" + APPID;
sendRequest(url);
}
function sendRequest (url) {
var xmlhttp = new XMLHttpRequest ();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse (xmlhttp.responseText);
var weather = {};
weather.icon = data.weather[0].icon;
weather.dir = direction (data.wind.deg);
weather.wind = mph (data.wind.speed) + "mph";
weather.temp = K2C (data.main.temp) + "°C";
weather.loc = data.name;
weather.hum = data.main.humidity + "%";
weather.sUp = formatDate (data.sys.sunrise);
weather.sDown = formatDate (data.sys.sunset);
update (weather);
}
};
xmlhttp.open ("GET", url, true);
xmlhttp.send ();
}
function K2F (k) {
return Math.round(k * (9 / 5) - 459.67);
}
function K2C (k) {
return Math.round (k - 273.15);
}
function mph (ms) {
return Math.round (ms / 0.44704);
}
function kmph (ms) {
return Math.round (ms * 3.6);
}
function formatDate (t) {
var date = new Date (t * 1000);
var h = date.getHours ();
var m = "0" + date.getMinutes ();
var s = "0" + date.getSeconds ();
return h + ":" + m.substr(-2) + ":" + s.substr(-2);
}
function direction (deg) {
var range = 360 / 16;
var low = 360 - (range / 2);
var high = (low + range) % 360;
var angles = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
for (var i in angles) {
if (deg >= low && deg < high) {
return angles[i]
}
low = (low + range) % 360;
high = (high + range) % 360;
}
return "N";
}

Phonegap geolocation distance between coordinates

I tried to calculate the distance between two coordinates in javascript.
More specifically the distance between one set of static coordinates and my current position taken from the geolocation cordova plugin.
Here's my code:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
var onSuccess = function(position) {
document.getElementById("content").innerHTML = 'Success, attempting calculation...';
var lla = position.coords.latitude;
var llo = position.coords.longitude;
document.getElementById("content").innerHTML =
'GPS Position: ' + calcTheDistance(lla, llo).d + 'Metres';
};
var onError = function(error) {
document.getElementById("content").innerHTML =
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n';
};
function refrGps() {
document.getElementById("content").innerHTML = 'Loading...';
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
function calcTheDistance(lati1, long1) {
var r = 6371000; //Meters
var joschLat = 50.1109221;
var joschLon = 8.6821267;
var la1 = lati1;
var la2 = joschLat;
var lat1 = lati1.toRadians();
var lat2 = joschLat.toRadians();
var lo1 = long1;
var lo2 = joschLon;
var la2minla1 = (la2-la1).toRadians();
var lo2minlo1 = (lo2-lo1).toRadians();
var cal = Math.sin(la2minla1 / 2) * Math.sin(la2minla1 / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(lo2minlo1/2) * Math.sin(lo2minlo1/2);
var c = 2* Math.atan2(Math.sqrt(cal), Math.sqrt(1-cal));
d = r * c;
};
I tried to rewrite it several times with no luck.
For the calculation I referred to this: http://www.movable-type.co.uk/scripts/latlong.html
The page you referenced contains a library of functions already implemented in Javascript. If you include these in your app, the calculation becomes trivial:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
var onSuccess = function(position) {
document.getElementById("content").innerHTML = 'Success, attempting calculation...';
var sourceLl = new LatLon(position.coords.latitude, position.coords.longitude);
document.getElementById("content").innerHTML =
'GPS Position: ' + calcTheDistance(sourceLl) + 'Metres';
};
var onError = function(error) {
document.getElementById("content").innerHTML =
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n';
};
function refrGps() {
document.getElementById("content").innerHTML = 'Loading...';
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
function calcTheDistance(sourceLl) {
var joschLat = 50.1109221;
var joschLon = 8.6821267;
var joschLl = new LatLon(joschLat, joschLon);
return joschLl.distanceTo(sourceLl);
};
So I figured it out after reading #DaveAlden 's Answer, thanks by the way!
toRadians(); is not a standard Javascript function, so after I added this and rewrote my code a bit, it worked fine.
Here's the working code
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
var onSuccess = function(position) {
document.getElementById("content").innerHTML = 'Success, attempting calculation...';
var lla = position.coords.latitude;
var llo = position.coords.longitude;
var dst = 'Distance: ' + calcTheDistance(lla, llo) + ' Metres';
document.getElementById("content").innerHTML = dst;
};
var onError = function(error) {
document.getElementById("content").innerHTML =
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n';
};
function refrGps() {
document.getElementById("content").innerHTML = 'Loading...';
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
function toRadians(num) {
return num * Math.PI / 180;
};
function calcTheDistance(lati1, long1) {
var r = 6371000; //metres
var joschLat = 50.1109221;
var joschLon = 8.6821267;
var la1 = lati1;
var la2 = joschLat;
var lat1 = toRadians(lati1);
var lat2 = toRadians(joschLat);
var lo1 = long1;
var lo2 = joschLon;
var la2minla1 = toRadians(la2-la1);
var lo2minlo1 = toRadians(lo2-lo1);
var cal = Math.sin(la2minla1 / 2) * Math.sin(la2minla1 / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(lo2minlo1/2) * Math.sin(lo2minlo1/2);
var c = 2* Math.atan2(Math.sqrt(cal), Math.sqrt(1-cal));
var d = r * c;
return Math.round(d);
};

Categories

Resources