简体   繁体   中英

Here Maps Geocoder Javascript API - Postcode problems

I am creating a script to find locations starting from UK Postcodes using the Here Maps Geocoder Javascript API. The code seems to work fine, but on the postcode BT45 7PX I got the error

TypeError: result.Response.View[0] is undefined

The code I am using is as follows:

var platform = 0;
var postcode = 0; /*random value*/

$(document).ready(function(){
    platform = new H.service.Platform({
        app_id: '(myapp_id)',
        app_code: '(myapp_code)',
        useCIT: true
        });

    document.getElementById('searchInput').value.toUpperCase();
    postcode = contentRead.replace(/\s+/g, '');
    geocode(postcode);
})

function geocode(postcode){
    var geocoder = platform.getGeocodingService(),
    geocodingParameters = {
        searchText: postcode
    };

    geocoder.geocode(
        geocodingParameters,
        onSuccess,
        onError
        );
}


function onSuccess(result){
    var location = result.Response.View[0].Result[0];
    var city = location.Location.Address.City;
    var lat = location.Location.DisplayPosition.Latitude;
    var lng = location.Location.DisplayPosition.Longitude;
    console.log('location: ');
    console.log(location);
    console.log('latitude: '+lat);
    console.log('longitude: '+lng);
    $('#rightResult').append('<div>The postcode searched points to... <strong>'+city+'</strong></div>');
}


function onError(error){
    alert('Ooops, something went wrong, please try again!');
}

Any clue about why the code doesn't work properly with BT45 7PX ?

Trying with a basic JSON call ( http://geocoder.api.here.com/6.2/geocode.json?app_id=(myapp_id)&app_code=(myuapp_code)&searchtext=BT45%207PX ) I found that the call works if I leave the space between, but removing it, as I was doing, it doesn't anymore. This doesn't happen with other postcodes.

We will be able to help you better if you post the API response, but given your edit, it looks like removing the space simply causes the API to not return a result. Because of this you are trying to access an array index that simply doesn't exist. At some point in your code you will probably want to handle for this scenario, so now would be a good time to do that. Post the response (without a valid result) and I will help you figure out what to use to determine wether a proper result was found or not.

It is always good to have null checks when processing a response, something like the following should work

if(response && response.Response && response.Response.View[0] && response.Response.View[0].Result[0]) {
    // Process Result
}

Regarding the postal code with spaces, this seems to be an issue with postal codes in UK.

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