简体   繁体   中英

Google Maps Distance Matrix error “originAddresses”: [“nan, nan”]

I'm developing a search field for an application, where the user types an address or establishment name and the system dynamically returns I've used the Google Maps Distance Matrix API to do the calculation but the parameter 'origins' does not accept the value passed by the geolocation of the HTML that returns

{"rows": [{"elements": [{"status": "ZERO_RESULTS"}]}], "originAddresses": ["nan, nan"] , "destinationAddresses": ["- 25.494926, -49.294444999999996"]}

The 'destinationAddress' I manually put to test.

function initMap() {
    const autocomplete = new google.maps.places.Autocomplete(document.getElementById('searchBox'));

    var x = document.getElementById("geolocation");

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Não foi possível obter sua localização atual. A versão atual do navegador é antiga ou a detecção de localização está desabilitada.";
    }

    function showPosition (position) {
        //Put on div the id geolocation the logitude and latitude
        x.innerHTML = position.coords.latitude + ", " + position.coords.longitude

        getDistance();
    }
}

function getDistance() {
    // Get what is written in the div with id geolocation and put in variable cdata
    // Giving alert in cdata correctly displays the user's current longitude and latitude
    var cdata = document.getElementById('geolocation').innerHTML;
    var origin1 = new google.maps.LatLng(cdata); //retorn ['nan, nan'] ?? wtf
    var destination = new google.maps.LatLng(-25.494926, -49.294445);

    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
        {
            origins: [origin1],
            destinations: [destination],
            travelMode: 'DRIVING'
        }, callback);
}

function callback(response, status) {
    var x = document.getElementById("geolocation");
    alert(JSON.stringify(response));
}

$("#searchForm").keyup(function () {
    var search = $("#searchBox").val();
    $.post('includes/establishmentSearch.inc.php', {searchForm: search}, function(data){
        $('#searchResponse').html(data);
        if (search == '') {
            $("#searchResponse").empty();
            $(".groupSepare").show();
        } else {
            $(".groupSepare").hide();
        }
    });
});

Detail: I'm only working with latitude and longitude, and I'm not using any google maps because I only need location data.

cdata is a string. The google.maps.LatLng constructors takes two numbers as arguments.

var cdata = document.getElementById('geolocation').innerHTML;
var coords = cdata.split(",");
var origin1 = new google.maps.LatLng(coords[0], coords[1]); 

proof of concept fiddle

code snippet:

 function initMap() { const autocomplete = new google.maps.places.Autocomplete(document.getElementById('searchBox')); var x = document.getElementById("geolocation"); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Não foi possível obter sua localização atual. A versão atual do navegador é antiga ou a detecção de localização está desabilitada."; } function showPosition(position) { //Put on div the id geolocation the logitude and latitude x.innerHTML = position.coords.latitude + ", " + position.coords.longitude getDistance(); } } function getDistance() { // Get what is written in the div with id geolocation and put in variable cdata // Giving alert in cdata correctly displays the user's current longitude and latitude var cdata = document.getElementById('geolocation').innerHTML; console.log(cdata); var coords = cdata.split(","); var origin1 = new google.maps.LatLng(coords[0], coords[1]); var destination = new google.maps.LatLng(-25.494926, -49.294445); var service = new google.maps.DistanceMatrixService(); service.getDistanceMatrix({ origins: [origin1], destinations: [destination], travelMode: 'DRIVING' }, callback); } function callback(response, status) { var x = document.getElementById("geolocation"); alert(JSON.stringify(response)); } $("#searchForm").keyup(function() { var search = $("#searchBox").val(); $.post('includes/establishmentSearch.inc.php', { searchForm: search }, function(data) { $('#searchResponse').html(data); if (search == '') { $("#searchResponse").empty(); $(".groupSepare").show(); } else { $(".groupSepare").hide(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="searchBox" value="Nebraska" /> <div id="geolocation"></div> <script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM