Using a string as GPS coordinates - javascript

I am using javascript and I have GPS coordinates in the form of a string and I am trying to put those into the google.maps.LatLng(59.327383, 18.06747) format but am having trouble deciding how to do it. I have a variable:
GPSlocation = "(37.700421688980136, -81.84535319999998)"
and I need it to go into that google.maps.LatLng(num, num) format. How can I put this string in there?
Thanks!

You can use standard string operations to extract the values:
var GPSlocation = "(37.700421688980136, -81.84535319999998)";
var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ")
var Lat = parseFloat(LatLng[0]);
var Lng = parseFloat(LatLng[1]);
google.maps.LatLng(Lat, Lng)

You can create an Array from it (using JSON.parse), and then use apply to 'feed' the coordinates to the method:
GPSlocation = JSON.parse( "(37.700421688980136, -81.84535319999998)"
.replace(/^\(/,'[')
.replace(/\)$/,']')
);
google.maps.LatLng.apply(null,GPSlocation);
Alternatively you can replace the brackets and use split to create an Array, and call the method LatLng the regular way. This method requires an extra conversion to Number of the Array values.
GPSlocation = "(37.700421688980136, -81.84535319999998)"
.replace(/^\(|\)$/,'')
.split(',');
google.maps.LatLng(+GPSlocation[0],+GPSlocation[1]);
To retrieve an Array of coordinates from the string, you could also use:
GPSlocation = ''.slice.call('(37.700421688980136, -81.84535319999998)',
1,this.length-1)
.split(',')
.map(function(a){return +a;});
google.maps.LatLng(GPSlocation[0],GPSlocation[1]);

Related

Remove double quotes from array in JavaScript

How to remove double quotes from array in JavaScript?
my data, this polygon coordinates google maps
["{lat:-8.089057558100306,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.1782636642456}", "{lat:-8.087867882261257,lng:112.17800617218018}", "{lat:-8.089057558100306,lng:112.15251445770264}"]
to
[{lat:-8.089057558100306,lng:112.15251445770264}, {lat:-8.100954123313068,lng:112.15251445770264}, {lat:-8.100954123313068,lng:112.1782636642456}, {lat:-8.087867882261257,lng:112.17800617218018}, {lat:-8.089057558100306,lng:112.15251445770264}]
after remove double quotes my data must be still array, not string.
Thanks
If you can't alter the results you get above, you have to work around it.
var a = ["{lat:-8.089057558100306,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.1782636642456}", "{lat:-8.087867882261257,lng:112.17800617218018}", "{lat:-8.089057558100306,lng:112.15251445770264}"];
a = a.map(function(o){
var d = o.split(',').map(function(b){
return Number( b.replace(/(}|{lat:|lng:)/g, '') );
/* OR
b.replace('{lat:', '')
.replace('lng:', '')
.replace('}', '');
*/
});
return {
lat: d[0],
lng: d[1]
};
});
console.log(a);
Iif you really trust that data, evaling it is the simplest way to convert it:
let data = ["{lat:-8.089057558100306,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.1782636642456}", "{lat:-8.087867882261257,lng:112.17800617218018}", "{lat:-8.089057558100306,lng:112.15251445770264}"];
console.log(data.map(s => eval('null,' + s)));
(The null, is just there to make eval treat this as an expression instead of a { block }.)
However, as always, eval can introduce code injection vulnerabilities if you're not sure about where the data comes from. And really, you should figure out how the data got this way in the first place and fix it up into a useful format there.
You can try regex
var arr = ["{lat:-8.089057558100306,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.1782636642456}", "{lat:-8.087867882261257,lng:112.17800617218018}", "{lat:-8.089057558100306,lng:112.15251445770264}"]
arr = arr.map(function(item) {
var match = item.match(/lat:(\-?[0-9\.]+),lng:(\-?[0-9\.]+)/);
return {lat: +match[1], lng: +match[2]};
})
console.log(arr)

How to efficently parse a string of latitude/longitude points to an array of object in JS?

I receive a series of latitude/longitude points in a string (from a third party) with the following format (of course there can be more than 2 set of pairs):
[(49.0000, -105.0000), (49.0000, -110.0000)]
and I want to convert that string to an array of object like this:
[{lat: 49.0000, lng: -105.0000}, {lat: 49.0000, lng: -110.0000}]
I want to do this in pure JavaScript but would be open to use jQuery if it simplifies the code a lot.
Currently, I use some regex and substrings on the source string but I'm wondering if there more elegant way to do this conversion that I could have missed?
You can try:
// your third party string
var string = '[(49.0000, -105.0000), (49.0000, -110.0000)]';
// make it a valid array of positions
// - basically changing parentheses to brackets
var array = string.replace(/[()]/g, function(d){
return {
'(' : '[',
')' : ']',
}[d];
});
// now it is valid, parse it
array = JSON.parse(array);
// each item has lat/long in the positions 0/1, respectively
var result = array.map(function(item){
return {
lat: item[0],
lng: item[1],
};
});
console.log(result);
Use JSON.parse(dataString) to achieve array of objects with lat/lng fields. If it's not solve your problem, than provide addition information.

Convert lat long string into google maps API LatLng Object

I am trying to convert a lat long string (53.3603, -6.315050000000042) into a google maps object in this format: B: -6.26747649999993 k: 53.339251
I have used this function which works for the long but returns Nan for the lat.
function getLatLngFromString(ll) {
var lat = ll.replace(/\s*\,.*/, ''); // first 123
var lng = ll.replace(/.*,\s*/, ''); // second ,456
var locate = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
return locate;
}
;
I am storing the lat long in a html tag as it called to a list view connected to a map. It is stored here in the correct format however when I retrieve it using the jQuery .attr it converts it to a string.
var location = $(this).closest('.allList').attr("position");
Any help would be greatly appreciated.
Assuming the lat/lng string looks like "10.5, -0.51"
function getLatLngFromString(ll) {
var latlng = ll.split(/, ?/)
return new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));
}
Should work

concatenate string from JSON

I would like to pull the longitudes and latitudes from an ESRI geometry and concatenate them in to a long string (to be used in an API call).
I am struggling with how to accomplish this
The ESRI documentation for geometry (geometry specs) shows the structure of the object but my API call needs the latitude/longitudes in the following format:
long1,lat1,long2,lat2,long3,lat3 ... long1, lat1
All I have to do is process the long/lats a little bit. Making a very simple example from the ESRI documentation
MyTest = {
"rings": [
[
[-97.06138, 32.837],
[-97.06133, 32.836],
[-97.06124, 32.834],
[-97.06127, 32.832],
[-97.06138, 32.837]
]
],
"spatialReference": {
"wkid": 4326
}
};
alert(JSON.stringify(MyTest.rings[0]));
Will give me the rings (the Longitudes/Latitudes) (notice the first long/lat is repeated as the last long/lat)
I cannot seem to figure out how to strip off the [ and ] to create a string with just the longitudes and latitudes. For instance:
myTest2 = MyTest.rings[0]; // get the longitudes and latitudes
myTest3 = JSON.stringify(myTest2);
myTest4 = myTest3.replace("[","");
alert(JSON.stringify(myTest2));
alert(JSON.stringify(myTest4));
The replace will strip off one of the brackets but I cannot get it to do a global replace like this post stack javascript replace because my programming environment is all within ColdFusion and I need the quotes around the pattern.
Can someone point out my error please ? Thanks !
You may try this (Example) using join():
MyTest = { "rings": [...] };
var str = MyTest.rings.join();
Result (in str) would be:
-97.06138,32.837,-97.06133,32.836,-97.06124,32.834,-97.06127,32.832,-97.06138,32.837
You have an object, use it - don't play with the stringified version.
var coords = MyTest.rings[0];
var list = [];
for ( var i = 0; i < coords.length; ++i )
{
list.push(coords[i][0]);
list.push(coords[i][1]);
}
var str = list.join(',');
// str is now "-97.06138,32.837,-97.06133...(etc.)"
DEMO: http://jsfiddle.net/gunderjt/B5wsK/2/
MyTest.rings[0].join()
and join with no parameters delineates with commas automatically
These are absolute basics, but you don't need to replace anything. [] is just an JavaScript array and not a string.
MyTest.rings.map(function (r) { return r.join(','); }).join(',');
// "-97.06138,32.837,-97.06133,32.836,-97.06124,32.834,-97.06127,32.832,-97.06138,32.837"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

passing jquery element reference to vanilla javascript

I'm trying to do something very simple with javascript but can't quite get my head around it. I'm not sure what format I should be passing the var address as.
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(address);
});
});
function getMap(address) {
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(address),
...
});
}
I'm getting an error when I pass the JQuery ref to normal javascript: TypeError: 'undefined' is not an object (evaluating 'a.position=b'). Any help appreciated.
If I read this correctly and you posted this code correctly, you pass a non-existing object lasting to getMap(), while you want to pass the address object. What happens if you correct this?
jQuery instances are just normal javascript objects like all others, so there should not be a problem.
You're passing the variable latLng to getMap, but its value isn't set. Your ready function at the top should look like this:
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(this);
});
});
Or, if you're trying to pass the address variable you set, make your ready function look like this:
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(address);
});
});
Your issue has nothing to do with jquery or javascript.
You are passing the wrong data into the LatLng method.
You need to pass in two parameters to the LatLng method:
...
var mapDiv = $('#mapDiv')[0], // also make sure the div is a regular dom node
lat = 7.1011123,
lng = 4.6667566;
function getMap(address) {
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng( lat, lng ), // you must pass in two parameters
...
});
}
If you are trying to get your LatLng coords from a text div then you need to convert your strings into floats.
Supposing the following html is what you use:
<ul>
<li class="latlng">7.4142335,3.1296874</li>
<li class="latlng">8.4135039,-5.1256828</li>
<li class="latlng">-14.4101158,-5.2810335</li>
</ul>
Then this would be the function running getMap() for every .latlng list item:
$('.latlng').each(function( i ){
var address = $(this).text();
address = address.split(','); // convert your text into an array
// send in your lat and lng strings parsed as floats
getMap(
parseFloat( address[0] ),
parseFloat( address[1] )
);
});

Categories