-1

I have some coordinates in a custom field:

45.4924038,9.2040718

And I am loading them into a map like this:

var mylatLg = "<?php echo get_post_meta($id, 'usp-custom-90', true); ?>";
var mylatLg = mylatLg.split(',');

console.log(mylatLg[0]);
console.log(mylatLg[1]);

var lat = parseInt(mylatLg[0]);
var lng = parseInt(mylatLg[1]);

The first console.log gives:

45.4924001
9.206260499999985

The second control.log says:

45
9

If I load the markers as per the following below, it gives me a wrong position (as it is 45,9)

  var marker = new google.maps.Marker({
      map: map,
      position: {lat: parseInt(mylatLg[0]), lng: parseInt(mylatLg[1])},

If I load the markers as per the following below

 var marker = new google.maps.Marker({
      map: map,
      position: {lat: mylatLg[0], lng: mylatLg[1]},

It gives

InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number

How can I run 45.4924038,9.2040718 as I have in the custom field?

rob.m
  • 9,843
  • 19
  • 73
  • 162

2 Answers2

4

Instead try with + unary operator which somewhat works like parseFloat():

var lat = +mylatLg[0];
var lng = +mylatLg[1];

console.log(+"45.4924001");
console.log(+"9.206260499999985");
Jai
  • 74,255
  • 12
  • 74
  • 103
  • perfect, it works. What does it do tho? I didn't know – rob.m Nov 22 '18 at 14:09
  • 1
    FYI [parseint-vs-unary-plus](https://stackoverflow.com/questions/17106681/parseint-vs-unary-plus-when-to-use-which) will help you on understanding. – Jai Nov 22 '18 at 14:13
3

You need to use parseFloat and not parseInt. This will parse the strings to floats. Or just try to cast it using Number, e.g. Number('9.206260499999985') will produce the float 9.206260499999985.

Pehota
  • 116
  • 5