OpenLayers OpenLayers

SimpleAjax

A simple example of AJAX that uses OpenLayers.loadURL

In the main body after OpenLayers.map is called;

/*
 * Now go fetch the LonLat from a zip passed in the URL
 *
 */
    var args = new OpenLayers.Util.getArgs();
    if (args.zip) {
        zip = parseInt(args.zip);
        var uri = "http://somewhere.over.the.rainbow/cgi-bin/zip2lonlat.py?zipcode="+zip
        OpenLayers.loadURL(uri, '', this, setZipCode);
    }

zip2lonlat is a simple python script that returns a lon/lat pair back to the client js.

Now for the callback setZipCode, that was referenced in the OpenLayers.loadURL() above

/*
 * Look at the Ajax response from zip2lonlat
 */
function setZipCode(response) {
    if (response.responseText.indexOf('no results') == -1) {
        var zip_data = response.responseText.replace(/^\s*/,'').replace(/\s*$/,'').replace(/[^0-9-.,]/g,'').replace(/\[/,'').replace(/\]/,'').split(',');
        var lon1 = parseFloat(zip_data[0]).toFixed(6);
        var lat1 = parseFloat(zip_data[1]).toFixed(6);
        var lon2 = parseFloat(zip_data[2]).toFixed(6);
        var lat2 = parseFloat(zip_data[3]).toFixed(6);

        if (zip_data) {
            map.zoomToExtent(new OpenLayers.Bounds(lon1, lat1, lon2, lat2));
        } else {
            map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
        }
    }
}