openlayers實(shí)現(xiàn)圖標(biāo)拖動(dòng)獲取坐標(biāo)
本文實(shí)例為大家分享了openlayers實(shí)現(xiàn)圖標(biāo)拖動(dòng)獲取坐標(biāo)的具體代碼,供大家參考,具體內(nèi)容如下
本文所涉及的技術(shù)如下:
openlayers加載國(guó)家天地圖和浙江天地圖,圖標(biāo)拖動(dòng)獲取位置,openlayers動(dòng)畫。
效果如下:

代碼如下:
var map;
var dataResult;
var app = {};
/**
* @constructor
* @extends {ol.interaction.Pointer}
*/
app.Drag = function() {
ol.interaction.Pointer.call(this, {
handleDownEvent: app.Drag.prototype.handleDownEvent,
handleDragEvent: app.Drag.prototype.handleDragEvent,
handleMoveEvent: app.Drag.prototype.handleMoveEvent,
handleUpEvent: app.Drag.prototype.handleUpEvent
});
/**
* @type {ol.Pixel}
* @private
*/
this.coordinate_ = null;
/**
* @type {string|undefined}
* @private
*/
this.cursor_ = 'pointer';
/**
* @type {ol.Feature}
* @private
*/
this.feature_ = null;
/**
* @type {string|undefined}
* @private
*/
this.previousCursor_ = undefined;
};
ol.inherits(app.Drag, ol.interaction.Pointer);
/**
* @param {ol.MapBrowserEvent} evt Map browser event.
* @return {boolean} `true` to start the drag sequence.
*/
app.Drag.prototype.handleDownEvent = function(evt) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) {
return feature;
});
if (feature) {
this.coordinate_ = evt.coordinate;
this.feature_ = feature;
}
return !!feature;
};
/**
* @param {ol.MapBrowserEvent} evt Map browser event.
*/
app.Drag.prototype.handleDragEvent = function(evt) {
var deltaX = evt.coordinate[0] - this.coordinate_[0];
var deltaY = evt.coordinate[1] - this.coordinate_[1];
var geometry = this.feature_.getGeometry();
geometry.translate(deltaX, deltaY);
this.coordinate_[0] = evt.coordinate[0];
this.coordinate_[1] = evt.coordinate[1];
//console.log(this);
};
/**
* @param {ol.MapBrowserEvent} evt Event.
*/
app.Drag.prototype.handleMoveEvent = function(evt) {
if (this.cursor_) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) {
return feature;
});
var element = evt.map.getTargetElement();
if (feature) {
if (element.style.cursor != this.cursor_) {
this.previousCursor_ = element.style.cursor;
element.style.cursor = this.cursor_;
}
} else if (this.previousCursor_ !== undefined) {
element.style.cursor = this.previousCursor_;
this.previousCursor_ = undefined;
}
}
};
/**
* @return {boolean} `false` to stop the drag sequence.
*/
app.Drag.prototype.handleUpEvent = function() {
dataResult={"coordinatex":this.coordinate_[0],"coordinatey":this.coordinate_[1]};
this.coordinate_ = null;
this.feature_ = null;
return false;
};
/**
* @desc 定義坐標(biāo)系統(tǒng)與范圍
*/
var worldExtent = [-180,-90,180,90 ];// 世界范圍
var projection = ol.proj.get("EPSG:4326"); //4326坐標(biāo)
var projectionExtent = projection.getExtent();
/**
* @desc 去掉第0層的天地圖分辨率信息,不會(huì)出現(xiàn)縮放到最后是空白的現(xiàn)象
*/
var tdtResolutions = [ 0.02197265625, 0.010986328125, 0.0054931640625,
0.00274658203125, 0.001373291015625, 0.0006866455078125,
0.00034332275390625, 0.000171661376953125, 0.0000858306884765625,
0.00004291534423828125, 0.000021457672119140625,
0.0000107288360595703125,0.00000536441802978515625,0.000002682209014892578125,0.0000013411045074462890625
];
/**
*@desc 與分辨率信息需要每層嚴(yán)格對(duì)應(yīng)起來
*/
var matrixIds = [6, 7, 8, 9, 10, 11, 12, 13, 14];
var matrixIdszj=[15, 16, 17,18,19,20]
/**
* @desc 天地圖格網(wǎng)信息
*/
var tdtGrid = new ol.tilegrid.WMTS( {
origin : ol.extent.getTopLeft(projectionExtent),
resolutions : tdtResolutions.slice(0, 9),
matrixIds : matrixIds
});
var tdtGridzj = new ol.tilegrid.WMTS( {
origin : ol.extent.getTopLeft(projectionExtent),
resolutions : tdtResolutions.slice(9, 15),
matrixIds : matrixIdszj
});
/**
* @desc 國(guó)家天地圖圖層
*/
var wmtsVecLayer = new ol.layer.Tile( {
source : new ol.source.WMTS( {
layer : 'vec',
style : 'default',
version : '1.0.0',
matrixSet : 'c',
format : 'tiles',
url : 'http://t{0-6}.tianditu.com/vec_c/wmts?tk=key',
tileGrid : tdtGrid,
wrapX : true
}),
minResolution: 0.0000858306884765625,
maxResolution: 0.02197265625
});
var wmtsAnnoLayer = new ol.layer.Tile( {
source : new ol.source.WMTS( {
layer : 'cva',
style : 'default',
version : '1.0.0',
matrixSet : 'c',
format : 'tiles',
url : 'http://t{0-6}.tianditu.com/cva_c/wmts?tk=key',
tileGrid : tdtGrid,
wrapX : true
}),
minResolution: 0.0000858306884765625,
maxResolution: 0.02197265625
});
/**
* @desc 浙江天地圖圖層
*/
var zJVecLayer = new ol.layer.Tile( {
source : new ol.source.WMTS( {
style : 'default',
version : '1.0.0',
wrapX : true,
layer : 'ZJEMAP',
matrixSet:'TileMatrixSet0',
format : 'image/png',
url : 'http://srv.zjditu.cn/ZJEMAP_2D/wmts',
tileGrid : tdtGridzj,
wrapX : true
}),
minResolution: 0.0000013411045074462890625,
maxResolution: 0.0000858306884765625,
});
var zJAnnoLayer =new ol.layer.Tile( {
source : new ol.source.WMTS( {
style : 'default',
version : '1.0.0',
wrapX : true,
layer : 'ZJEMAPANNO',
matrixSet : 'TileMatrixSet0',
format : 'image/png',
url : 'http://srv.zjditu.cn/ZJEMAPANNO_2D/wmts',
tileGrid : tdtGridzj,
wrapX : true
}),
minResolution: 0.0000013411045074462890625,
maxResolution: 0.0000858306884765625,
});
var devVectorSource = new ol.source.Vector();
var devVectorLayer = new ol.layer.Vector({
source:devVectorSource,
style:pointStyleFunction
});
//定位點(diǎn)要素
var positionFeature = new ol.Feature();
positionFeature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
}));
function flyLocation(center) {
var duration = 1000; //持續(xù)時(shí)間(毫秒)
var start = +new Date();
//移動(dòng)效果
var pan = ol.animation.pan({
duration: duration, //設(shè)置持續(xù)時(shí)間
source: /** @type {ol.Coordinate} */(map.getView().getCenter()),
start: start
});
//反彈效果
/* var bounce = ol.animation.bounce({
duration: duration, //設(shè)置持續(xù)時(shí)間
resolution: 2 * map.getView().getResolution(), //4倍分辨率
start: start
}); */
map.beforeRender(pan); //地圖渲染前設(shè)置動(dòng)畫效果(pan+bounce)
map.getView().setCenter(center); //平移地圖
map.getView().setZoom(18); //放大地圖
}
//創(chuàng)建定位點(diǎn)矢量圖層(featuresOverlay)
var featuresOverlay = new ol.layer.Vector({
source: new ol.source.Vector({
features: [positionFeature]
})
});
function GetRequest() {
var url = decodeURI(location.search); //獲取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
var type;
//初始坐標(biāo)
var data={"coordinatex":(GetRequest().x?GetRequest().x:121.54610300015),"coordinatey":(GetRequest().y?GetRequest().y:29.876429)};
/**
* @desc 初始化
* @return
*/
$(function(){
//document.getElementById("topBar").style.fontSize=document.getElementById("topBar").width;
initMap();
// showJq();
dataResult=data;
loadData(data);
});
/**
* @desc:初始化地圖
* @return
*/
function initMap() {
map = new ol.Map( {
// 設(shè)置地圖控件,默認(rèn)的三個(gè)控件都不顯示
controls: ol.control.defaults({
attribution: false,
zoom: false
}),
view : new ol.View({
// extent:[120.320631,30.311294,120.332057,30.319126],//定義地圖容器范圍,不是地圖的初始化范圍
center : [121.54610300015,29.876429],
zoom :18,
projection : projection,
maxZoom: 20,
minZoom: 9
}),
// logo: false, // 不顯示logo
// logo: 'logo.png', // 用一個(gè)圖片 logo.png 作為logo
//logo: {src: 'images/logo.png', href: 'http://www.openstreetmap.org/'}, // 點(diǎn)擊能跳轉(zhuǎn)到對(duì)應(yīng)頁(yè)面
layers : [ wmtsVecLayer,wmtsAnnoLayer,zJVecLayer,zJAnnoLayer],
target : 'map',
interactions: ol.interaction.defaults({
pinchRotate:false
}).extend([new app.Drag()])
});
map.addLayer(devVectorLayer);
map.addLayer(featuresOverlay); //添加定位點(diǎn)標(biāo)注(矢量要素圖層)
};
function loadData(dataJson){
// var dataJson = $.parseJSON(data);
//map.getView().fit(initExtent,map.getSize());
devVectorSource.clear();
//isCheck = dataJson.dev.isCheck;
var devArr = dataJson;
if(dataJson.coordinatex&&dataJson.coordinatey){
var features = new Array();
if(devArr.coordinatex && devArr.coordinatey){
var feature = new ol.Feature(new ol.geom.Point([parseFloat(devArr.coordinatex),parseFloat(devArr.coordinatey)]));
feature.setProperties(devArr);
features.push(feature);
}
devVectorSource.addFeatures(features);
var num = parseInt(Math.random()*features.length,10);
var ft = features[num];
var ptCoord = ft.getGeometry().getCoordinates();
map.getView().setCenter(ptCoord);
map.getView().setZoom(18);
}
}
function pointStyleFunction(feature,resolution){
var imgPath = 'images/location.png';
return [new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
// opacity: 0.9,
src: imgPath
})
})]
}
function defaultPoints()
{
loadData(data);
}
function uploadPoints(){
console.log(dataResult);
}
function closeWindow()
{
if(confirm("確定要退出嗎?")){
var browserName=navigator.appName;
if (browserName=="Netscape"){
window.opener=null;
window.open('', '_self', '');
window.close();
}
if (browserName=="Microsoft Internet Explorer") {
window.parent.opener = "whocares";
window.parent.close();
}
}
}
HTML文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>定位</title>
<link rel="stylesheet" href="ol.css" >
<style type="text/css">
#map{
width:100%;
height:100%;
position:absolute;
margin:0;
}
body{
margin: 0;
padding: 0;
}
#topBar{
position:absolute;
z-index:99;
top:5px;
height:70px;
font-size:200%;
background-color:#263344;
color:#ffffff;
left:10px;
right:10px;
}
#uploadPoints{
float:right;
color:#fff;
margin-top:14px;
margin-right:7px;
}
#topBar_left{
float:left;
color:#fff;
margin-top:14px;
margin-left:7px;
}
#menu{
width:100%;
height:20px;
padding:5px 10px;
font-size:14px;
font-family:"微軟雅黑";
left:10px;
}
</style>
</head>
<body>
<div id="topBar" style="visibility:visible">
<div id="topBar_left">
<a id="close" onclick="closeWindow();" >關(guān)閉</a>
<a id="default" onclick="defaultPoints();" >| 默認(rèn)位置</a>
</div>
<div id="uploadPoints" onclick="uploadPoints();" >使用此位置</div>
</div>
<div id='map' class="hescgis-map"></div>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ol.js"></script>
<script type="text/javascript" src="map.js"></script>
</body>
</html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript 在各個(gè)瀏覽器中執(zhí)行的耐性
經(jīng)常會(huì)遇到這樣一個(gè)情況:瀏覽器彈出對(duì)話框,提示腳本運(yùn)行時(shí)間過長(zhǎng),詢問“停止”還是“繼續(xù)”。那究竟各個(gè)瀏覽器是如何判斷在什么時(shí)候才彈出此對(duì)話框呢?2009-04-04
JS動(dòng)態(tài)圖片的實(shí)現(xiàn)方法完整示例
這篇文章主要介紹了JS動(dòng)態(tài)圖片的實(shí)現(xiàn)方法,結(jié)合完整實(shí)例形式分析了JavaScript鼠標(biāo)響應(yīng)與頁(yè)面元素屬性動(dòng)態(tài)變換相關(guān)操作技巧,需要的朋友可以參考下2020-01-01
js實(shí)現(xiàn)的仿新浪微博完美的時(shí)間組件升級(jí)版
本博客沒有華麗的布局,只求樸實(shí)的js的代碼,只為js代碼愛好者提供,一周大概會(huì)出1-2篇js前沿代碼的文章.只是代碼,不說技術(shù)2011-12-12
js設(shè)置cookie過期當(dāng)前時(shí)間減去一秒相當(dāng)于立即過期
這篇文章主要介紹了設(shè)置js cookie過期(相當(dāng)于清除瀏覽器對(duì)應(yīng)名稱的cookie)使用方法是當(dāng)前時(shí)間減去一秒相當(dāng)于立即過期2014-09-09
JavaScript與ActionScript3兩者的同性與差異性
接觸JavaScript和ActionScript3也有近5年的時(shí)間了,它們都是應(yīng)用比較廣泛的腳本語言.接下來通過本文給大家介紹JavaScript與ActionScript3兩者的同性與差異性,感興趣的朋友一起學(xué)習(xí)吧2016-09-09
javascript attachEvent和addEventListener使用方法
attachEvent與addEventListener區(qū)別 適應(yīng)的瀏覽器版本不同,同時(shí)在使用的過程中要注意2009-03-03

