Legacy Archive (2013): Originally written in Chinese on doubixie.com and translated into English for this edition. All archive posts · Home

Cross-Origin Issues with OpenLayers GetFeatureInfo

Original Chinese title: 使用openlayer getfeature 出现的跨域问题

It's been a long time since my last update. Things have been busy, and if I don't write something down every day, I end up feeling like I have no idea what I even accomplished—just letting another day slip by doing nothing.
Anyway, let's get straight to the point. I've always been interested in frontend development. Since I come from a GIS background, to make graduating a bit smoother down the road, I picked a few GIS-related frontend tools to dig into. OpenLayers is a very efficient JavaScript library for frontend map rendering. Its source code is open on GitHub—you can just fork it to pull it down, and referencing it is super straightforward.

A Few Notes on Referencing

1. When calling GeoServer's WMS service, you need to include deprecated.js—mainly because you need to create a container.
2. I won't go into detail on publishing services with GeoServer. I used processed shapefiles (.shp), and PostGIS is great too. Make sure to get a decent server—GeoServer's performance still isn't quite as strong as a certain commercial server.

Describing the Cross-Origin Issue

tiled = new OpenLayers.Layer.WMS(
    "test:农华101_7月_平均气温平均shp - Tiled", "http://202.205.91.115:8080/geoserver/test/wms",
        {
            LAYERS: 'test:农华101_7月_平均气温平均shp',
                STYLES: '',
                format: format,
                tiled: true,
                tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
        },
        {
            buffer: 0,
            displayOutsideMaxExtent: true,
            isBaseLayer: true,
            yx : {'EPSG:3752' : false}
        }
    );

This is a WMS layer I’d already published and am calling here—I’ll skip the specific parameters. I used Apache as the web server, and after publishing, the map displayed normally.
// Register a click event to query layer attribute data on click
map.events.register(‘click’, map, function (e) {

document.getElementById('nodelist').innerHTML = "Loading... please wait...";
    var params = {
        REQUEST: "GetFeatureInfo",
        EXCEPTIONS: "application/vnd.ogc.se_xml",
        BBOX: map.getExtent().toBBOX(),
        SERVICE: "WMS",
        INFO_FORMAT: 'text/html',
        QUERY_LAYERS: map.layers[0].params.LAYERS,
        FEATURE_COUNT: 50,
        Layers: 'test:农华101_7月_平均气温平均shp',
        WIDTH: map.size.w,
        HEIGHT: map.size.h,
        format: format,
        styles: map.layers[0].params.STYLES,
        srs: map.layers[0].params.SRS};
// Without deprecated.js included, OpenLayers.loadURL will throw an undefined error
OpenLayers.loadURL("http://202.205.91.115:8080/geoserver/test/wms", params, this, setHTML, setHTML);
OpenLayers.Event.stop(e);

No matter what I tried, GetFeatureInfo just wouldn’t return any data. After Googling around, I found out why: it uses XML data, and because the web server and map server run on two different ports (80 and 8080), it triggers a cross-origin issue—and browsers don’t allow cross-origin requests (Chrome, Firefox, IE8+, Safari).

Solution

The idea: OpenLayers actually provides a cross-origin proxy script, though it’s written in Python, so make sure Python is installed on your server. Copy the code below and save it to your website’s root directory:

 #!/usr/bin/env python // This is your Python path on Linux; on a Windows server it should be something like path/python.exe -u.

import urllib2
import cgi
import sys, os

    # Designed to prevent Open Proxy type stuff.

    allowedHosts = ['www.openlayers.org', 'openlayers.org',
            'labs.metacarta.com', 'world.freemap.in',
            'prototype.openmnnd.org', 'geo.openplans.org',
            'sigma.openplans.org', 'demo.opengeo.org',
            'www.openstreetmap.org', 'sample.azavea.com',
            'v2.suite.opengeo.org', 'v-swe.uni-muenster.de:8080',
            'vmap0.tiles.osgeo.org', 'www.openrouteservice.org',
            'maps.wien.gv.at','your server address + port']

method = os.environ["REQUEST_METHOD"]

if method == "POST":
    qs = os.environ["QUERY_STRING"]
    d = cgi.parse_qs(qs)
    if d.has_key("url"):
    url = d["url"][0]
    else:
        url = "your server address + port"
else:
    fs = cgi.FieldStorage()
    url = fs.getvalue('url', "your server address + port")

try:
    host = url.split("/")[2]
    if allowedHosts and not host in allowedHosts:
           print "Status: 502 Bad Gateway"
        print "Content-Type: text/plain"
        print
        print "This proxy does not allow you to access that location (%s)." % (host,)
           print
        print os.environ

    elif url.startswith("http://") or url.startswith("https://"):

        if method == "POST":
            length = int(os.environ["CONTENT_LENGTH"])
            headers = {"Content-Type": os.environ["CONTENT_TYPE"]}
            body = sys.stdin.read(length)
            r = urllib2.Request(url, body, headers)
            y = urllib2.urlopen(r)
        else:
            y = urllib2.urlopen(url)

        # print content type header
        i = y.info()
        if i.has_key("Content-Type"):
            print "Content-Type: %s" % (i["Content-Type"])
        else:
            print "Content-Type: text/plain"
        print

        print y.read()

        y.close()
    else:
        print "Content-Type: text/plain"
        print
        print "Illegal request."

except Exception, E:
    print "Status: 500 Unexpected Error"
    print "Content-Type: text/plain"
    print
    print "Some unexpected error occurred. Error text was:", E

Or just modify the proxy.cgi file under the OpenLayers examples folder the same way and drop it into your website’s root directory.
Then, in your frontend init function, add the following declaration:

OpenLayers.ProxyHost = 'proxy.cgi?url=';

Finally, configure Apache so it can run Python scripts, and you’re good to go.

Over