Skip to content

Instantly share code, notes, and snippets.

@chrislkeller
Last active January 27, 2023 16:26
Show Gist options
  • Save chrislkeller/3553967 to your computer and use it in GitHub Desktop.
Save chrislkeller/3553967 to your computer and use it in GitHub Desktop.
Convert string Lat/Long to number for Google Maps API.

Convert string Lat/Long to number for Google Maps API

When sending Lat/Long values to the Google Maps API for something like setCenter(), it wants an number value. But the value we pull from an option menu like the one below is a string.

<select id="searchString" onchange="zoomToAddress(this.value);">
<option value="">--Select All--</option>
<option value="43.138092,-89.747988">Luckenbooth Cafe</option>
<option value="43.017218,-89.831479">Aunt Mary's Hooterville Inn</option>
</select>

So we want to convert the above strings to numbers that the Maps API can use. We'll place the following inside a function called zoomToAddress.

First we get the value from the option menu as a string and set it to a variable.

var searchString = document.getElementById('searchString').value;

Then we set a variable to find the position of the comma in the string.

var commaPos = searchString.indexOf(',');

Use parseFloat to conver the string to a number while parsing out the Latitude value.

var coordinatesLat = parseFloat(searchString.substring(0, commaPos));

And we do the same for the Longitude.

var coordinatesLong = parseFloat(searchString.substring(commaPos + 1, searchString.length));

Those variables are combined into a new google maps LatLng pair.

var centerPoint = new google.maps.LatLng(coordinatesLat, coordinatesLong);

Then we can use the setCenter() method from the Maps API.

map.setCenter(centerPoint);
@ozzir
Copy link

ozzir commented Nov 12, 2019

I have a 41.31035240 latitude value that comes as a string.
when a use
parseFloat('41.31035240')
it returns 41.3103524 as a number but without the last zero digit and the maps api does not find the location.
Any ideas?

@chrislkeller
Copy link
Author

@ozzir - This StackOverflow link gets into some of what you are experiencing...

parseFloat() turns a string into a floating point number. This is a binary value, not a decimal representation

https://stackoverflow.com/questions/4868556/how-do-i-stop-parsefloat-from-stripping-zeroes-to-right-of-decimal

@AlejandroBec94
Copy link

Wow haha It's funny because I tried it like that and it didn't work

lat={Number(item.coordinates.split(',')[0])}
lng={Number(item.coordinates.split(',')[1])}

@hibah564
Copy link

centerPoint return NaN !
let temp="36.862499,10.195556";
var commaPos = temp.indexOf(',');
var coordinatesLat = parseFloat(temp.substring(0, commaPos));
var coordinatesLong = parseFloat(temp.substring(commaPos + 1, temp.length));

    var centerPoint = new google.maps.LatLng(coordinatesLat, coordinatesLong);

CCC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment