1 引入资源库iclient8 SuperMap-8.1.1-15523.js 、字符集 zh-CN.js
我这里SuperMap.Include.js动态引入了上述文件,最后提供给大家链接
<script src="../../app/static/lib/iclient/libs/SuperMap.Include.js">/script>
<script src="../../app/static/lib/iclient/libs/TDT.js"></script>`
页面新建div元素
<div id="map" style=""> </div>
<script src="../../app/static/js/map.js"></script>
<script type="text/javascript">
InitMap();
</script>
2 新建map.js文件,加载地图
var map;
var tianVecLayer, tianImgLayer, tianLabelLayer; //天地图相关图层 Vec地图 Img影像 Label标注
var curmaptype; //底图类型,"vec","img"
function InitMap() {
map = new SuperMap.Map("map", { //map为页面上的div id
controls: [
new SuperMap.Control.MousePosition(),
new SuperMap.Control.Navigation({
dragPanOptions: {
enableKinetic: true
}
})],
allOverlays: true, projection: "EPSG:4490" //此处设置地图投影
});
map.minZoom = 8; //最小缩放值
map.maxZoom = 20; //最大缩进值
initBaseControls(); //初始地图控件
changeToTianImg(); //加载天地图地图
//地图中心点 - 此处为长沙市
var poi = {
x:112.98626,
y:28.25591
};
//设置地图中心点和投影
map.setCenter(new SuperMap.LonLat(poi.x, poi.y).transform(
new SuperMap.Projection("EPSG:4490"),
map.getProjectionObject()), 12);
}
//初始化地图的基本控件,导航、比例尺、缩放
function initBaseControls() {
var container = map.getSize();
//地图平移控件
var panzoombar = new SuperMap.Control.PanZoomBar();
panzoombar.showSlider = true;
panzoombar.showCompass = false;
map.addControl(panzoombar, new SuperMap.Pixel(container.w - 100, container.h - 250));
map.addControl(new SuperMap.Control.KeyboardDefaults());
//地图缩放控件
var navigation = new SuperMap.Control.Navigation({
dragPanOptions: { enableKinetic: true },
//屏蔽双击放大事件
defaultDblClick: function (event) {
return;
}
});
map.addControl(navigation, new SuperMap.Pixel(container.w - 100, 50));
//比例尺控件
map.addControl(new SuperMap.Control.ScaleLine(),
new SuperMap.Pixel(50, container.h - 70));
}
//初始化天地图地图
function initTianLayers() {
if (tianImgLayer == null || tianImgLayer == undefined) {
tianVecLayer = new SuperMap.Layer.TDT("地图", "vec");
tianImgLayer = new SuperMap.Layer.TDT("影像", "img");
tianLabelLayer = new SuperMap.Layer.TDT("影像标注", "img_label");
}
curmaptype = "img";
}
//点击事件切换地图
function changeToTianImg() {
removeAllLayers();
curmaptype = "img";
initTianLayers();
tianVecLayer.isBaseLayer = true;
tianImgLayer.isBaseLayer = true;
tianLabelLayer.isBaseLayer = false;
map.addLayers([tianVecLayer, tianImgLayer, tianLabelLayer]);
}
//移除所有图层
function removeAllLayers() {
var length = map.getNumLayers();
for (var i = 0; i < length; i++) {
map.removeLayer(map.layers[0]);
}
}
3 使用proxy代理地图瓦片
在JavaWeb工程的web.xml中添加代理器
<!--动态REST地图切片接入服务-->
<servlet>
<servlet-name>proxycontroller</servlet-name>
<!--这里是proxyController的地址-->
<servlet-class>com.supermap.application.common.ProxyController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>proxycontroller</servlet-name>
<url-pattern>/proxy/tile</url-pattern>
</servlet-mapping>
新增代理类ProxyController
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by SuperMap-dev on 2014/11/5.
* 动态REST麻点图层切片访问代理服务,如果能解决Tomcat不同工程跨域可并入data
* (解决跨域、网速慢;高效切片获取)
*/
public class ProxyController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/png");
response.setCharacterEncoding("utf-8");
String urlStr = request.getParameter("url");//获取请求参数URL
OutputStream outputStream = response.getOutputStream();
urlStr = this.handleUrl(urlStr);
URL url = new URL(urlStr);
this.getImage(url,outputStream);
}
//缓存读取瓦片,显示稳定高效
private void getImage(URL url, OutputStream out){
try {
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
byte[] buffer = new byte[512];//缓冲字节数,值小适用网络宽,降低丢包率
int count = 0;
while ((count = in.read(buffer)) > 0){
out.write(buffer, 0, count);
}
out.close();
in.close();
connection.disconnect();
}catch (MalformedURLException e) {
// e.printStackTrace();
System.out.println("URL地址出错!");
}catch (IOException io){
System.out.println("请求切片,连接超时!");
// io.printStackTrace();
}catch (Exception e){
// e.printStackTrace();
}
}
private void getBufferImage(URL url, OutputStream outputStream){
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setUseCaches(true);
BufferedInputStream bufferedInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
int length = httpURLConnection.getContentLength();
byte[] buffer = new byte[50];
int readByte = 0;
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
while (readByte < length) {
int num = bufferedInputStream.read(buffer, 0, 50);
readByte += num;
bufferedOutputStream.write(buffer, 0, 50);
}
if (length == -1) {
int count = bufferedInputStream.read(buffer, 0, 50);
while (count != -1) {
bufferedOutputStream.write(buffer, 0, count);
count = bufferedInputStream.read(buffer, 0, 50);
}
}
bufferedInputStream.close();
bufferedOutputStream.close();
} catch (IOException e) {
System.out.println("请求切片连接超时!");
e.printStackTrace();
}
}
/**
* url参数预处理
* @param url
* @return
*/
private String handleUrl(String url){
//将参数中临时替换的字符替换回来
url = url.replaceAll("\\$","&");
url = url.replace("!", "?");
//将参数中的中文进行编码
Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = pattern.matcher(url);
String zhStr = "";
while (m.find()) {
String t = m.group();
zhStr += t;
}
if(!"".equals(zhStr)){
try {
url = url.replaceAll(zhStr,URLEncoder.encode(zhStr,"utf-8"));
} catch (UnsupportedEncodingException e) {
System.out.println("编码转换出错! 地图参数中含有中文字符");
e.printStackTrace();
}
}
return url;
}
}
4 TDT,js中修改proxyUrl方法的代理地址为你本地项目地址,我的是app
/**
* Class: SuperMap.Layer.TDT此图层可以访问 天地图 的地图服务。
*
* Inherits from: - <SuperMap.Layer.CanvasLayer>
*/
SuperMap.Layer.TDT = SuperMap
.Class(
SuperMap.CanvasLayer,
{
/**
* APIProperty: name {String}图层名称,默认为“Tianditu”,防止初始化时未设置图层名
*
*/
name: "Tianditu",
/**
* Property: url {String}默认的TianDiTu的地图服务器地址
*/
/*
* Tianditu底图(球面墨卡托投影)
*/
url: "http://t0.tianditu.com/DataServer?T=vec_w&X=${x}&Y=${y}&L=${z}",
/**
* Constructor: SuperMap.Layer.AMap
* 创建天地图图层,可以浏览天地图地图 Example: (code)
*
* var layer = new SuperMap.Layer.Tianditu(layerName, type, projection);
* type {vec, img, label}
* //将Layer图层加载到Map对象上 map.addLayer(layer);
* //出图,map.setCenter函数显示地图 //加载的天地图图层默认为墨卡托投影,所以定位需要转换
* map.setCenter( new SuperMap.LonLat(110,39.5 ).transform(
* new SuperMap.Projection("EPSG:4326"),
* map.getProjectionObject() ), 4 );
*
* (end)
*
*
* Parameters: name - {String} 图层名称
* layerType - {String} 图层类型,包括底图、底图标签、影像、影像标签
*/
initialize: function (name, layerType, projection) {
this.name = name;
var baseUrl = "http://t3.tianditu.com/DataServer?T=";
if (layerType == "vec")
this.url = baseUrl + "vec_c";//地图
else if (layerType == "img")
this.url = baseUrl + "img_c";//影像
else if (layerType == "vecLabel")
this.url = baseUrl + "cva_";
else if (layerType == "img_label")
this.url = baseUrl + "cia_c";//标签
else if (layerType == "ter")
this.url = baseUrl + "ter_";
else if (layerType == "terLabel")
this.url = baseUrl + "cta_";
var options = {
projection: "EPSG:4326",
numZoomLevels: 15
};
if (projection == 1) { //WGS84 经纬度
this.url += "c";
options.projection = "EPSG:4490"
} else if (projection == 2) { //EPSG:900913 球面墨卡托
this.url += "w";
options.projection = "EPSG:900913";
}
this.url += "&X=${x}&Y=${y}&l=${z}&tk=28b495e4df789d971d2ae77b01a55a55";
this.url = this.proxyUrl(this.url);
SuperMap.CanvasLayer.prototype.initialize.apply(this, [
name, this.url, {}, options ]);
},
proxyUrl: function (url) {
var purl = this.getBaseUrl() + "/app/proxy/tile?url=";
var _param = url; //this.url;
_param = this.replaceChar(_param);
return purl + _param;
},
getBaseUrl: function () {
var loc = window.location;
if (loc.origin) {
return loc.origin;
}
return loc.protocol + "//" + loc.host;
},
replaceChar: function (url) {
url = url.replace(/&/g, "$");
url = url.replace(/\?/g, "!");
return url;
},
/**
* Method: clone
*/
clone: function (obj) {
if (obj == null) {
obj = new SuperMap.Layer.TDT(this.name);
}
obj = SuperMap.CanvasLayer.prototype.clone.apply(this,
[ obj ]);
return obj;
},
/**
* APIMethod: destroy 解构Tianditu类,释放资源。
*/
destroy: function () {
var me = this;
me.name = null;
me.url = null;
SuperMap.CanvasLayer.prototype.destroy.apply(me,
arguments);
},
/**
* Method: getTileUrl 获取瓦片的URL。
*
* Parameters: xyz - {Object} 一组键值对,表示瓦片X, Y, Z方向上的索引。
*
* Returns {String} 瓦片的 URL 。
*/
getTileUrl: function (xyz) {
var me = this, url;
url = me.url;
url = SuperMap.String.format(url, {
x: xyz.x,
y: xyz.y,
z: xyz.z
});
return url;
},
CLASS_NAME: "SuperMap.Layer.TDT"
});
为大家奉上TDT.js代码
注意事项
页面的div必须给一个初始大小
SuperMap Iclicent 8 资源类可以在我的下载里找到
其他网络地图只需更改TDT.js文件里的URL链接地址
**