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

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!

Related

Filter specific properties and sum the values

I have a Leaflet map with polygons, you can click on each polygon to select them and there is an info window "L.control" that shows the values for the selected polygon. As you continue click on polygons the info window add values for each selected and you get total values for all selected polygons. All this is fine but I need to get down to more detailed sum for specific properties like the example below of regions. If ten polygons are selected I want to differentiate the total amount for regions with properties "REGION SOUTH" and "REGION NORTH" as well as the total of all.
This is the code I'm using, to sum the totals of different properties is no problem but how do you sum for defined properties?
How and where can I add a kind of filter solution that sum only the properties I want?
$.each(statesData.features, function(index, feature) {
var name = `${feature.properties.ZIPCODE} ${feature.properties.Name} ( ${feature.properties.average_time} - ${feature.properties.CITY})`
placenames.push(name);
zipcodes[name] = feature.properties.ZIPCODE;
time = feature.properties.average_time
});
etc....
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
var total3 = 0
var total4 = 0
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount, // sum amount for all regions
total1 += properties.average_time, // in seconds
total2 += properties.distance,
total3 += properties.amount, // amount for Region South only
total4 += properties.amount, // amount for Region North only
// Convert seconds to timeformat
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
total3: total3
total4: total4
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Total amount: <b>' + details.total + ' st</b><br>' +
'Region South amount: <b>' + details.total3 + ' st</b><br>' +
'Region North amount: <b>' + details.total4 + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.resultTime, details.total, details.total2, details.total3, details.total4);
};
detailsselected.addTo(map);
FeatureSelected:
function checkExistsLayers(feature) {
var result = false
for (var i = 0; i < featuresSelected.length; i++) {
if (featuresSelected[i].ZIPCODE == feature.properties.ZIPCODE) {
result = true;
break;
}
};
return result
}
This is part of the json file structure:
var statesData = new L.LayerGroup;
var statesData = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"ZIPCODE":12345,"CITY":"LONDON","REGION":"REGION SOUTH","amount":1088,"average_time":26150,"distance":2.2},"geometry":{"type":"MultiPolygon","coordinates":...
I did try the following but that did not work...
function filt_north (feature){
if (feature.properties.REGION === 'REGION NORTH' )
return true;
}
total4 += filt_north.(properties.amount), // amount for Region North only
The filt_north function you wrote looks good, just add a filt_south filter to get the south region and do:
let filteredResults = featuresSelected.filter(
result => filt_north(result.feature) || filt_south(result.feature)
);
for (let result of filteredResults) {
var properties = result.feature.properties;
...
Tried your solution, seems it breaks the code and totals is not added up at all = stopped working. I did this, should it be done in a different way?
Filter function:
function filt_south (feature){
if (feature.properties.REGION === 'REGION SOUTH')
return true;
}
function filt_north (feature){
if (feature.properties.REGION === 'REGION NORTH')
return true;
}
Then changed to this (I must be doing something wrong here):
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
var total3 = 0
var total4 = 0
let filteredResults = featuresSelected.filter(
result => filt_south(result.feature) || filt_north(result.feature)
);
for (let result of filteredResults) {
var properties = result.feature.properties;
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount, // sum amount for all regions
total1 += properties.average_time,
total2 += properties.distance,
total3 += filt_south (properties.amount), // amount for Region South only
total4 += filt_north (properties.amount) // amount for Region North only
// Convert seconds to timeformat
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
total3: total3
total4: total4
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Total amount: <b>' + details.total + ' st</b><br>' +
'Region South amount: <b>' + details.total3 + ' st</b><br>' +
'Region North amount: <b>' + details.total4 + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.resultTime, details.total, details.total2, details.total3, details.total4);
};
detailsselected.addTo(map)

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

Why markers do not move correcly on map

Sample of JSON data (from the comments):
[{"id":"280","id_vehicle":"VL0847810531","lat":"30.0761","longi":"1.01981","spee‌​d":"144","time":"2014-12-03 12:07:23"},{"id":"202","id_vehicle":"VL0645210631","lat":"34.7344","longi":"7.32‌​019","speed":"78","time":"2014-12-03 11:55:44"}]
function updateLocations(jsonData)
{
for (i=0 ;i< jsonData.length; i++) //for all vehicles
{
var id_vehicle = jsonData[i]["id_vehicle"];
var lat = jsonData[i]["lat"];
var lng = jsonData[i]["longi"];
var speed = jsonData[i]["speed"];
var str_time = jsonData[i]["time"];
/************************update list*******************************/
var state_icon, marker_icon, state;
var time = moment(str_time);
var last_10_Min = moment().subtract({minutes: 60 + 10});
if(time.isBefore(last_10_Min)) //if before 10 last minutes
{
state_icon = INACTIVE_IMG;
marker_icon = INACTIVE_VEHICLE;
state = "INACTIVE";
}
else //if befor
{
if(jsonData[i]["speed"] > 10) //if > 2 km/h then running
{
state_icon = RUN_IMG;
marker_icon = RUN_VEHICLE;
state = "RUN";
}
else
{
state_icon = STOP_IMG;
marker_icon = STOP_VEHICLE;
state = "STOP";
}
}
$("#state_img_"+id_vehicle).attr("src", state_icon);
$("#state_img_"+id_vehicle).attr('state',state);
$("#select_"+id_vehicle).attr("disabled" , false ); // enable selection
/************************update location info*******************************/
var locationInfo = new Array();
img = "<img src=" + state_icon + " width='16' height='16' >";
locationInfo.push("Etat : " + state + " " + img + "<br>");
locationInfo.push("Latitude : " + lat + "<br>");
locationInfo.push("Longitude : " + lng + "<br>");
locationInfo.push("Vitess: " + speed + " klm/h<br>");
locationInfo.push("Temps : " + str_time + "<br>");
$("#info_location_" +id_vehicle).html(locationInfo.join(""));
/*****************update vehicles on map *************/
try {
cBox = $("#select_"+id_vehicle);
if(cBox.is(':checked')) //update selected only
{
//get marker index
var id_map = cBox.attr("id_map");
//change title
title = "Latitude: "+ lat + "\nLongitude: " + lng + "\nSpeed: " + speed + "\nTime: " + str_time;
arrayMarker[id_map].setTitle(title); //update title
arrayMarker[id_map].setIcon(marker_icon);
//move marker
arrayMarker[id_map].setPosition( new google.maps.LatLng(parseFloat(lat),parseFloat(lng)) );
}
}catch(error){};
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
my question is why whene this function is executed (updating locations) just fisrt vehicle on map is moved correctly, the ohers are updated (title, icon ...) but do not move?
I noticed that , they move and return to their old location quickly.
Thanks for any suggestion.
finaly i found problem, it was here:
var marker = new MarkerWithLabel({......});
arrayMarker[id_map] = marker; //put marker in arrayMarker at indexMarker position
the bug occur whene i filled my arrayMarker using MarkerWithLabel (3th lib)
whene changed to native google.maps.Marker it work correcly:
var marker = new google.maps.Marker({......});
arrayMarker[id_map] = marker;

Categories

Resources