Grałem trochę z usługą DistanceMatrixService firmy Google. Poniższy kod działa, ale jak mogę przekazać inny parametr do funkcji wywołania zwrotnego lub pobrać jedną z wartości z wywołania zwrotnego?JavaScript Prześlij parametr do oddzwaniania lub ustaw zmienną wartość w DistanceMatrixStatus
Na przykład: Mam dwie div, które chcę pokazać różne wyniki (Results1 i Results2), więc myślę, że trzeba albo
przekazać inną wartość do funkcji GoogleMapDistance jak GoogleMapDistance (YourLatLong, DestLatLong, TheDiv)
lub móc pobrać obiekt wynikowy zewnętrznie poza wywołanie zwrotne document.getElementById ("Wyniki1"). InnerHTML = ResultStr;
lub ustawić innerHTM na zwróconą wartość funkcji document.getElementById ("Results1"). InnerHTML = GoogleMapDistance (YourLatLong, DestLatLong);
Utknąłem. Jak mogę to osiągnąć? Teraz wygląda na to, że będę w stanie uruchomić cały ten kod tylko raz i mieć tylko zapis do jednego elementu div.
<div id="Results1"></div>
<div id="Results2"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function GoogleMapDistance(YourLatLong,DestLatLong)
{
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
}, callback);
}
function callback(response, status)
{
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 + " (<i>" + duration + "</i>)";
}
}
document.getElementById("Results1").innerHTML = ResultStr;
}
}
var YourLatLong = "45.4049,-122.797997";
var DestLatLong1 = "47.468893,-122.227978";
var DestLatLong2 = "61.221274,-149.831545";
GoogleMapDistance(YourLatLong,DestLatLong1);
</script>
Dziękujemy! Poszedłem z twoim pierwszym rozwiązaniem. Działa świetnie. – Soren
Jeśli nie brakuje mi punktu w twojej pierwszej alternatywie, w treści tego 'callbacku (odpowiedź, status, element)' ponownie zostanie wywołany inny element 'callback (some_arg)' ... czyż nie? – SASM