简体   繁体   中英

GET from JavaScript, problems parsing XML? Or Maps API errors?

I'm trying to make an HTTP get from Javascript, calling Google Maps to get transit duration from A to B, and then parsing the resulting XML as follows:

function getTransitTime(match) {
    var homeBase = '<Address 1>';
    var distURL = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&key=API_KEY_I_GOT&mode=transit&arrival_time=1519977600&origins=' + homeBase + '&destinations=' + match;

    parser = new DOMParser();
    xmlDoc = parser.parseFromString(httpGet( distURL ), "text/xml");
    var finRet = $(xmlDoc).find('duration').text()
    return finRet;
}

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, true );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

I receive both the NoApiKeys and SensorNotRequired errors in the js console. What am I doing wrong?

There are probably even more problems with this:

  • I'm not sure how to deal with spaces in address 1 (and even worse, "match").

  • Duration has two sub-fields (one being text), not sure if parsing is correct. Note that my query works correctly in the browser (with the same API key) and the output XML is pasted below:

<DistanceMatrixResponse>
    <status>OK</status>
    <origin_address>New York, NY, USA</origin_address>
    <destination_address>Philadelphia, PA, USA</destination_address>
    <row>
        <element>
            <status>OK</status>
            <duration>
                <value>5100</value>
                <text>1 hour 25 mins</text>
            </duration>
            <distance>
                <value>145447</value>
                <text>145 km</text>
            </distance>
        </element>
    </row>
</DistanceMatrixResponse>

Any help? I wandered off trying to make something "simple" work, but ended up in the deep end :|

I've managed to fix this:

First, get permissions to make cross-origin requests to the maps API, by including the following in the extension's manifest.json:

"permissions": ["https://maps.googleapis.com/"] 

Next, change:

var finRet = $(xmlDoc).find('duration').text()

to

var finRet = $(xmlDoc).find('duration').find('text').text()

This works because the returned XML has a text tag nested inside the duration tag.

Lastly, the spaces in the URL for the maps call don't really make any difference. Thanks for everyone for reading and contributing. I'm still looking for a cleaner solution if there's one.

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