the google map api doesn't works - javascript

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>

Related

Negative goes positive when tying to convert DMS to Lat/lon

I've been sitting with an error for quite some time. I'm working with coordinates, trying to convert coordinates from Decimal Degrees to DMS and back again, with a checkbox.
This is current code (JS Fiddle):
https://jsfiddle.net/Mtihc/m2n8tejs/61/
HTML:
<label>Lat</label><input id="latitude" type="text" value="-8.3692° S"/>
<label>Long</label><input id="longtitude" type="text" value="115.1383° E"/>
<input id="dmstoggler" type="checkbox"/>
<br/>
<label id="dmstoggler_state">Decimal degrees</label>
JavaScript:
$("#dmstoggler").on('change', function (eventInfo) {
let longInput = document.getElementById("longtitude")
let latInput = document.getElementById("latitude")
if (eventInfo.target.checked) {
// convert to DMS
let long = parseFloat(longInput.value.replace(/° \w/, ""))
let lat = parseFloat(latInput.value.replace(/° \w/, ""))
let dms = convertDMS(lat, long)
longInput.value = dms.long;
latInput.value = dms.lat;
} else {
// convert back to long/lat
let longdms = longInput.value.replace(/[^\d\s]/g, "").split(' ').map(n => parseFloat(n))
let latdms = latInput.value.replace(/[^\d\s]/g, "").split(' ').map(n => parseFloat(n))
let latlong = convertLatLong(latdms, longdms)
longInput.value = latlong.long
latInput.value = latlong.lat
}
$("#dmstoggler_state").html(eventInfo.target.checked ? "DMS" : "Decimal degrees")
})
function toDegreesMinutesAndSeconds(coordinate) {
var absolute = Math.abs(coordinate);
var degrees = Math.floor(absolute);
var minutesNotTruncated = (absolute - degrees) * 60;
var minutes = Math.floor(minutesNotTruncated);
var seconds = Math.floor((minutesNotTruncated - minutes) * 60);
if (coordinate < 0) degrees *= -1;
return degrees + "° " + minutes + "' " + seconds;
}
function convertDMS(lat, lng) {
var latitude = toDegreesMinutesAndSeconds(lat);
var latitudeCardinal = lat > 0 ? "'' N" : "'' S";
var longitude = toDegreesMinutesAndSeconds(lng);
var longitudeCardinal = lng > 0 ? "'' E" : "'' W";
return {
lat: latitude + latitudeCardinal,
long: longitude + longitudeCardinal
}
}
function convertLatLong(lat, long) {
let dmslat = lat[0] + (lat[1]/60) + (lat[2]/3600)
let dmslong = long[0] + (long[1]/60) + (long[2]/3600)
dmslat = parseFloat(dmslat.toFixed(4))
dmslong = parseFloat(dmslong.toFixed(4))
if (lat[0] < 0) dmslat *= -1;
if (long[0] < 0) dmslong *= -1;
return {
lat: dmslat + "° " + (lat[0] > 0 ? "N" : "S"),
long: dmslong + "° " + (long[0] > 0 ? "E" : "W"),
}
}
As you can see it starts at: -8.3692° S
After converting from Lat / Lon to DMS (works great), converting back to Lat / lon is an issue. When converting back to Lat / Lon it returns the value.
When converting back to Lat / lon it returns: 8.3692° N
We suspect a math issue, but can't locate the specific issue. As you can se it goes from Negative South to Positive North, how can this be?
Thank you!

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?

Make Google maps callback wait for rest of functions to finish

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

Undefined Value When Converting Metrics

One of my recent projects is to successfully get the temperature to convert from Fahrenheit to Celsius. However, I have run into a problem that gives me an undefined value when I click my button. Should I be referring to the temperature value that I have requested from my API? I believe that my conversion within my weather function isn't running when I call it.
Here's my codepen.
https://codepen.io/baquino1994/pen/qXjXOM?editors=0010
HTML
<span id="temp"></span>
<button id="tempunit">F</button>
JS
function weather(){
function success(position){
var latitude = position.coords.latitude;
var longitude= position.coords.longitude;
// location.innerHTML = "Latitude:" + latitude+"°"+ "Longitude: " + longitude+'°';
var theUrl = url +apiKey + "/"+ latitude+","+ longitude +"?callback=?";
$.getJSON(theUrl, function(data){
$("#temp").html(data.currently.temperature)
$("#minutely").html(data.minutely.summary)
// currentTempInFahrenheit = Math.round(data.html.currently.temperature * 10) /
$("#tempunit").text(tempUnit);
$.ajax({
url:'https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=AIzaSyBpiTf5uzEtJsKXReoOKXYw4RO0ayT2Opc', dataType: 'json',
success: function(results){
$("#city").text(results.results[3].address_components[4].long_name)
$("#country").text(results.results[0].address_components[5].long_name)
}
}
)}
);
}
var location = document.getElementById("location");
var apiKey = "3827754c14ed9dd9c84afdc4fc05a1b3";
var url = "https://api.darksky.net/forecast/";
navigator.geolocation.getCurrentPosition(success);
// location.innerHTML = "Locating...";
}
$(document).ready(function(){
weather();
});
var tempUnit = "F";
var currentTempInFahrenheit;
$("#tempunit").click(function(){
var currentTempUnit = $("#tempunit").text();
var newTempUnit = currentTempUnit == "F" ? "C" : "F";
$('#tempunit').text(newTempUnit);
if(newTempUnit == "F"){
var celTemp = Math.round(parseInt($('#temp').text())*5/9 - 32);
$("#temp").text(celTemp + " " + String.fromCharcode(176));
}
else{
$("#temp").text(currentTempInFahrenheit + " " + String.fromCharCode(176));
}
})
try this, my browser blocked geolocation, when i mocked the location i was able to get the codepen to work.
var location = document.getElementById("location");
var apiKey = "3827754c14ed9dd9c84afdc4fc05a1b3";
var url = "https://api.darksky.net/forecast/";
// navigator.geolocation.getCurrentPosition(success);
var position = { coords: { latitude: 32, longitude: -96 } };
success(position);

Google maps api v2 to v3

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

Categories

Resources