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

前端 未结 4 762
既然无缘
既然无缘 2021-02-05 03:22
function initAutocomplete() {
    var lat=document.getElementById(\'lat\').value;
    var lng=document.getElementById(\'lng\').value;
    console.log(lat);
    console.l         


        
相关标签:
4条回答
  • 2021-02-05 03:48

    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'
        });
    }
    
    0 讨论(0)
  • 2021-02-05 03:52

    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'
    });}
    
    0 讨论(0)
  • 2021-02-05 04:01

    Just initialize parameters:

    function initMap(lat_ = 0, lon_ = 0) {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: lat_, lng: lon_},
            zoom: 10
        });
    }
    
    0 讨论(0)
  • 2021-02-05 04:02

    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));
    
    0 讨论(0)
提交回复
热议问题