Javascript Pass Parameter to Callback or Set Variable Value in DistanceMatrixStatus

前端 未结 1 1848
陌清茗
陌清茗 2020-12-19 08:30

I have been playing a little bit with Google\'s DistanceMatrixService. The code below works, but, how can I pass another parameter to the callback function or grab one of th

1条回答
  •  春和景丽
    2020-12-19 08:55

    You can't change how Google calls the callback, but you can let it call your own locally function as the callback and then have that (via a closure) call another callback after adding the desired extra argument like this:

    function GoogleMapDistance(YourLatLong,DestLatLong, item)
    {
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
        {
        origins: [YourLatLong],
        destinations: [DestLatLong],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false
        }, function(response, status) {callback(response, status, item)});
    }
    

    Or, you could just define your callback inline so it has access to the parent function variables directly:

    function GoogleMapDistance(YourLatLong,DestLatLong, item)
    {
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
        {
        origins: [YourLatLong],
        destinations: [DestLatLong],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false
        }, function callback(response, status)
        {
            // you can access the parent scope arguments like item here
            if (status == google.maps.DistanceMatrixStatus.OK)
            {
            var origins = response.originAddresses;
            var destinations = response.destinationAddresses;
              for (var i = 0; i < origins.length; i++)
              {
                  var results = response.rows[i].elements;
                  for (var j = 0; j < results.length; j++)
                  {
                      var element = results[j];
                      var from = origins[i];
                      var to = destinations[j];
                      var distance = element.distance.text;
                      var duration = element.duration.text;
                      var ResultStr = distance + "  (" + duration + ")";
                  }
              }
            document.getElementById("Results1").innerHTML = ResultStr;
            }
        }
    
    )}
    

    0 讨论(0)
提交回复
热议问题