openlayers是一個(gè)純javascript的web地圖客戶端框架,對(duì)開發(fā)平臺(tái)的適應(yīng)性非常強(qiáng),可以很容易的嵌入靜態(tài)http頁面、asp頁面、.net頁面、jsp頁面、j2ee頁面。由于openlayers采用AJAX架構(gòu),當(dāng)?shù)貓D服務(wù)器與web客戶端服務(wù)器不同時(shí),WMS中的getFeatureInfo,以及所有WFS功能接口不能正常工作。原因是各種瀏覽器禁止跨域訪問xml,解決的辦法很簡(jiǎn)單,使用代理(Proxy)。
根據(jù)應(yīng)用系統(tǒng)架構(gòu)的不同,代理的實(shí)現(xiàn)方式有很多種,包括web服務(wù)器內(nèi)置代理(如Apache)、cgi方式代理、php代理、jsp代理、aspx代理等。
openlayers官方提供了一個(gè)采用python編寫的cgi代理,推薦在Apache2.2下使用。
openlayers官方代理安裝步驟:
1、安裝Python2.5,記住安裝路徑。
2、將openlayers官方提供的proxy.cgi復(fù)制到apache的cgi-bin目錄下。
修改第一行Python25的安裝路徑,注意不要去掉最前面的#號(hào)。
修改allowedHosts中的geoserver/mapserver ip:geoserver/mapserver port部分。
3、打開conf目錄下的httpd.conf文件,修改cgi部分,例如:
<Directory "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
AddHandler cgi-script .cgi .py
保存后重新啟動(dòng)Apache,在瀏覽器地址欄中填入http://apache ip/cgi-bin/proxy.cgi,測(cè)試代理是否工作正常。
以下是proxy.cgi的內(nèi)容:
#!C:\Python25\python.exe
# -*- coding: utf-8 -*-
import urllib2
import cgi
import sys, os
# Designed to prevent Open Proxy type stuff.
allowedHosts = ['geoserver/mapserver ip:geoserver/mapserver port',
'www.openlayers.org',
'openlayers.org']
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 = "http://www.openlayers.org"
else:
fs = cgi.FieldStorage()
url = fs.getvalue('url', "http://www.openlayers.org")
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
備注:部署在同一個(gè)機(jī)器、不同服務(wù)器上(相同ip,不同端口號(hào))同樣是跨域訪問。例如地圖服務(wù)器geoserver在tomcat,端口8080,應(yīng)用系統(tǒng)在Apache或IIS,端口80),這種情況下只有IE6能夠正常訪問,條件是將ip地址加入可信站點(diǎn)列表,IE7、IE8、FF3.6都會(huì)禁止訪問。