JS parseFloat creates Int when parsing ASP.NET MVC model data - javascript

I want to parse Model data as a float to Javascript variable, but I will always get no decimals
function initMap() {
var latitude = parseFloat("#Model.latitude");
var longitude = parseFloat("#Model.longitude");
console.log(latitude + " " + longitude);
}
For example, if Model.latitude = 46.3245 I will get 46.
I have also tried this: var latitude = parseFloat("#Model.latitude").toFixed(4); but I get 46.0000
What can I do ?

Related

Passing Multiple Variables to HTML via Javascript

I am trying to pass a latitude AND a longitude from one page to another after it has been calculated by the google API.
For a compass website. Want to pass the lat and long both to another page to be used on that page. I am trying to pass them via the javascript.
The Java passing the variables.
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
window.location.href = 'compass.html' + '#' + lat +'#' + long;
The Java recieving the variables
var latD = window.location.hash.substring(1);
var longD = window.location.hash.substring(2);
Instead of being split up they and being displayed together on the other page with the hash included. Like this:
-41.2864603?#174.77623600000004,
41.2864603?#174.77623600000004
I would like it to be like this:
-41.2864603
,174.77623600000004
Hash
The idea works, you just need to split the hash-string correctly.
//REM: On whatever.html
var lat = '-41.2864603';
var long = '174.77623600000004';
var tHref = 'compass.html' + '#' + lat +';' + long; //window.location.href = ..
//REM: On compass.html
var tHash = tHref.split('#').pop(); //window.location.hash.split('#').pop();
var tLat = tHash.split(';')[0];
var tLong = tHash.split(';')[1];
alert('Lat: ' + tLat + ', Long: ' + tLong);
QueryString
As another approach you could pass it as normal QueryString value like nbokmans recommended. Either separate or as stringified object. The difference is, that you need to implement your own js QueryString-Parser unless you get the values on the server. But you will find plenty of QueryString-Parsers on google.
Here is an example:
How can I get query string values in JavaScript?
localStorage
localStorage sounds like the easiest solution for me. You do not need to implement your own QueryString-Parser for it aswell. Just set it on whatever.html and read it on compass.html.
Check the example below:
https://developer.mozilla.org/de/docs/Web/API/Window/localStorage
//Set:
window.localStorage.setItem('whatever', JSON.stringify({lat: 1, long:2}));
//Get:
JSON.parse(window.localStorage.getItem('whatever'));
it should be like this :
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
window.location.href = 'compass.html?lat=' + '' + lat +'&longt=' + long;
To access these variables on that page,
const queryString = window.location.search;
console.log(queryString); // ?lat=19.234567&longt=73.23456
const urlParams = new URLSearchParams(queryString);
const lat = urlParams.get('lat')
const lng = urlParams.get('longt')
console.log(lat, lng);

ionic : - convert string to latitude, longitude append more digit at end?

i want to convertstring to latlng suppose string is 23.097278,72.446139 i want to convert it to latlng, when i split strings i get result as i want but when i converting to latlng it appends some digits at end of co ordinate
for example
centerPoint : (23.081295, 72.49794399999996), what i have done so far is below plz help me to solve it.
temp="23.097278,72.446139";
let temp1 = temp.split(',');
let coordinatesLat = temp1[0];
let coordinatesLong = temp1[1];
console.log("temp1 : " +coordinatesLong);
let centerPoint = new google.maps.LatLng(coordinatesLat, coordinatesLong);
console.log("centerPoint : " +centerPoint);
output in log
temp1 : 72.497944
centerPoint : (23.081295, 72.49794399999996)
Try to convert it to float
var latDouble = parseFloat(lat);
var longDouble = parseFloat(long);

Wrong Math Algorithm with javascript?

im trying to make some Algorithm function with javascript and get some problems
function Algorithm() {
var endone;
var endtwo;
var endtheend;
var v1 = document.getElementsByName("v1")[0].value; //worth to 91
var v2 = document.getElementsByName("v2")[0].value; //worth to 61
var v3 = document.getElementsByName("v3")[0].value; //worth to 20
endone = Math.round(v1 * 0.30);
endtwo = Math.round(((v2 + v3) / 2) * 0.70);
endtheend = endone + endtwo;
document.getElementById("ending").innerHTML = "end : " + endtheend;
}
if im doing the same Algorithm with a calculator im getting 55.65 , but when im trying to use this function somehow im getting 2169.
someone might know what is the problem and show me how to solve her?
The problem is that v1, v2 and v3 are not numbers. They are strings. So each calculation you make is relies on implicit conversions and operations between strings.
For instance, in the following snippete we have an implicit conversion of the the string value "91" to a double floating number and then the usual mulitplication is done.
var v1 = "91";
console.log(v1*0.3);
On the other hand below:
var v2 = "61";
var v3 = "20";
console.log((v2 + v3) / 2)
We have a string concatenation "61"+"20" results in a new string "6120" and then "6120" is implicitly converted to a double floating number and the division with 2 is done.
What's the solution ?
You have to parse these values either by using parseInt or parseFloat, like below:
var v2 = "61";
var v3 = "20";
console.log((parseInt(v2,10) + parseInt(v3,10)) / 2)
When you get an HTMLInputElement's value property, what you get is a string.
And the + operator applied to two strings merely concatenates them, so if for instance v2 == "7" and v3 === "0", when you do (v2 + v3), you'll get "70".
The solution to your problem is to simply pass the values through parseInt:
var v1 = parseInt(document.getElementsByName("v1")[0].value, 10);
var v2 = parseInt(document.getElementsByName("v2")[0].value, 10);
var v3 = parseInt(document.getElementsByName("v3")[0].value, 10);
// The second argument to parseInt isn't needed if you only target newer browsers.
I'd suggest you read up on type coercion in JavaScript for more info.
The issue is all of your values (v1, v2, v3) are String type. You need to convert them into Number first. So the following code should work :
function Algorithm() {
var endone;
var endtwo;
var endtheend;
var v1 = Number(document.getElementsByName("v1")[0].value);
var v2 = Number(document.getElementsByName("v2")[0].value);
var v3 = Number(document.getElementsByName("v3")[0].value);
endone = Math.round(v1 * 0.30);
endtwo = Math.round(((v2 + v3) / 2) * 0.70);
endtheend = endone + endtwo;
document.getElementById("ending").innerHTML = "end : " + endtheend;
}
you can also use parseInt if your value contains any alphabetic characters.

Cannot select JSON elements

I'm brand new to web dev but I'm trying to create a Weather app using the openweatherapp API: https://openweathermap.org/current#geo . The JSON object is below:
{"coord":{"lon":5.38,"lat":34.72},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":280.903,"pressure":1000.23,"humidity":65,"temp_min":280.903,"temp_max":280.903,"sea_level":1031.37,"grnd_level":1000.23},"wind":{"speed":8.5,"deg":317},"clouds":{"all":0},"dt":1486603649,"sys":{"message":0.3449,"country":"DZ","sunrise":1486621797,"sunset":1486660553},"id":2475612,"name":"Tolga","cod":200}
Here's my javascript:
$(document).ready(function() {
// findind my latitude and longitude
if(navigator.geolocation){
function success(position){
var lat = position.coords.latitude.toString();
var long = position.coords.longitude.toString();
$("p").html("latitude: " + lat + "<br>longitude: " + long);
// using the API to get the weather from those lat and long values
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long+"&appid=6a5aa3b59ebd571086cbd82be484ec8b", function(a){
temp = a[0].main.temp.toString();
hum = a[0].main.humidity.toString();
press= a[0].main.pressure.toString();
name = a[0].name;
$("h1").html(temp);
});
};
};
function failure(){
$("p").html("Not working");
};
navigator.geolocation.getCurrentPosition(success,failure);
});
The lat and long part is running fine but not the API for the weather.
Any help would be appreciated.
EDIT: Here's my codepen to make it simpler : https://codepen.io/tadm123/pen/OWojPx
Worked fine for me. Make sure that your browser has permission to know your location and that the computer has GPS. This probably will not work on a desktop.
Try manually setting the lat and long values and it should work.

Error calling method on NPObject exception with google earth

I'm trying to implement a Google Earth controller via Websockets.
I have a simple echo websockets server in c#, when i type a value in a textbox it just sends it back to the page (I plan to be able to directly send data from the server later).
My script to initialize google earth is pretty standard and works:
<script type="text/javascript">
google.load("earth", "1");
function init() {
google.earth.createInstance('map3d', initCallback, failureCallback);
StartServer();
}
function initCallback(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
// add a navigation control
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
// add some layers
ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
}
function failureCallback(errorCode)
{
}
</script>
(ge variable) is just the google earth instance.
Now in my server code, if I do:
ws.onmessage = function (evt)
{
inc.innerHTML += evt.data + '<br/>';
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
lookAt.setLatitude(lookAt.getLatitude() + 10);
lookAt.setLongitude(lookAt.getLongitude() + 20);
ge.getView().setAbstractView(lookAt);
};
Everything works (earth rotates a tiny bit).
Now if I do:
ws.onmessage = function (evt)
{
inc.innerHTML += evt.data + '<br/>';
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
lookAt.setLatitude(lookAt.getLatitude() + evt.data); //Here i try to use the data received
lookAt.setLongitude(lookAt.getLongitude() + 20);
ge.getView().setAbstractView(lookAt);
};
I get exception : Error calling method on NPObject
I tried to split string, convert to number, but always get the same error.
inc.innerHTML += evt.data + '<br/>';
always works tho.
EDIT:
I also tried :
var i = parseInt(d); //Works
but then when i call l
lookAt.setLatitude(i); //Exception
Any help appreciated
Try replacing evt.data with (+evt.data), the unary plus operator forces the value to a number.
I don't know the Google Earth API but if getLongitude was returning a string for some weird reason then that could produce the behaviour you're seeing there (string + number is a number but string + string is a string).
Ok sorted, pretty stupid thing, server was sending extra characters.
Feels a bit bad to have this generic error on parsing, having something like "string format invalid" would be bit more meaningful.
I had the exact same problem and it turned out that the lat/long values were too precise, so I did this to turn it into the maximum 6 decimal precision equivalent:
function Blah(lat, lon) {
//because the GPS is ridiculously accurate and
//google earth is not, we need to round to six decimals at most
lat = Math.round(lat * 1000000) / 1000000;
lon = Math.round(lon * 1000000) / 1000000;

Categories

Resources