error:InvalidValueError: setCenter: not a LatLng o

2019-03-25 14:59发布

问题:

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

回答1:

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'
    });
}


回答2:

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'
});}