Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error:InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number

function initAutocomplete() {
    var lat=document.getElementById('lat').value;
    var lng=document.getElementById('lng').value;
    console.log(lat);
    console.log(lng);


    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat:lat, lng:lng},
      zoom: 13,
      mapTypeId: 'roadmap'
    });}

it gives me the following error :

error:InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number

like image 512
ravneet Avatar asked Jul 03 '17 05:07

ravneet


4 Answers

The .value attribute of a HTMLInputElement returns the value as a string.

You have to parse the content of lat and lng with parseFloat() before passing it to the maps API

function initAutocomplete() {
    var lat = parseFloat(document.getElementById('lat').value);
    var lng = parseFloat(document.getElementById('lng').value);

    var map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: lat,
            lng: lng
        },
        zoom: 13,
        mapTypeId: 'roadmap'
    });
}
like image 93
Andreas Avatar answered Nov 15 '22 18:11

Andreas


Just add "+" before your variables:

function initAutocomplete() {
var lat=document.getElementById('lat').value;
var lng=document.getElementById('lng').value;

var map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: +lat, lng: +lng},
  zoom: 13,
  mapTypeId: 'roadmap'
});}
like image 29
anasmorahhib Avatar answered Nov 15 '22 16:11

anasmorahhib


Same error, slightly different scenario:

I kept getting this error (same as the OP) when trying to use the autocompleted lat/lng to update a map:

    var place = autocomplete.getPlace();
    var geo = place.geometry.location;
    loadMapAt(new google.maps.LatLng(geo.lat, geo.lng));

This "one weird trick" fixed it. Replacing the second line with:

    var geo = JSON.parse(JSON.stringify(place.geometry.location));
like image 1
Alex R Avatar answered Nov 15 '22 16:11

Alex R


I also was getting this error when using autocomplete which the above suggestions didn't solve. In my case, I was able to correct this by passing lat and lng as properties to my Gmaps element:

<Gmaps width={width}
       height={height}
       lat={lat}
       lng={lng}
       params = {{
           v: '3.exp',
           libraries: 'geometry, visualization, places', 
           key: GOOGLE_MAPS_API_KEY
       }}
       onMapCreated={this.onMapCreated}/>

This was using react-gmaps version 1.4.2.

like image 1
Graham Reid Avatar answered Nov 15 '22 18:11

Graham Reid