0

In this code below we invoke a JavaScript function from c# to calculate the time to get from point A to point B using google maps routing services. (calculateTripTime) this function should return an array with durations to get from point A to point B. (currently only filled with 1 duration) But it returns 'null'. Why does it return 'null' and how can i get the desired return from JavaScript to C# ?

when i call the following function it returns 0 like it is supposed to. so the code 'should' work.

returnNumber()
{
    return 0
}

The C# code:

public void DoStuff()
{
    if (webBrowser.InvokeRequired)
    {
        webBrowser.Invoke((MethodInvoker)delegate
        {
            object o = webBrowser.Document.InvokeScript("calculateTripTime", new object[] { "Amsterdam", "Zwolle" });
            MessageBox.Show(o.ToString());
        });
    }
    else
    {
        object o = webBrowser.Document.InvokeScript("calculateTripTime", new object[] { "Amsterdam", "Zwolle" });
        MessageBox.Show(o.ToString());
    }
}

The Javascript:

function calculateTripTime(start, end) 
{
    var service = new google.maps.DistanceMatrixService;

    service.getDistanceMatrix(
    {
        origins: [start],
        destinations: [end],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, 
    function (response, status) 
    {
        alert('duration filled');

        var originList = response.originAddresses;
        var destinationList = response.destinationAddresses;
        var results = response.rows[0].elements[0];

        return results.duration.value
    });
}
Daniel Corzo
  • 1,055
  • 2
  • 19
  • 32
Kars Barendrecht
  • 549
  • 10
  • 23
  • 1
    I think your function is returning before the service call completes. Have a look at this: http://stackoverflow.com/questions/19125716/wait-for-the-end-of-an-asynchronous-javascript-function-to-retrieve-a-result-de – Steve Wellens Dec 10 '15 at 15:10
  • I dont think this works for C#, javascript might wait for such a deferred answer but C# has already continued. I have tried implementing it but with no avail. – Kars Barendrecht Dec 14 '15 at 11:41

0 Answers0