openLayers2 画图标
openLayers2 画图标
介绍:这里主要是实现可以手动在地图上添加图标的方法.画出来的图标可以点击弹出提示信息.
直接上代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>创建一个简单的电子地图</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<!-- 加载OpenLayers类库 -->
<script src="../ol2/OpenLayers.js"></script>
<style type="text/css">
html,body{width: 100%; height: 100%; margin: 0; padding: 0;}
</style>
<!-- 关键代码在这里了 -->
<script type="text/javascript">
var map;
var markers ;
var drawPoint,pointLayer;
function init(){
// 使用指定的文档元素创建地图
map = new OpenLayers.Map("map");
// 创建一个OpenStreeMap raster layer
// 把这个地图增加到map中
var osm = new OpenLayers.Layer.OSM();
map.addLayer(osm);
// 设定视图缩放地图程度为最大
map.zoomToMaxExtent();
map.addControl(new OpenLayers.Control.LayerSwitcher());//图层控制
map.addControl(new OpenLayers.Control.MousePosition());//鼠标坐标
}
function PD(element) {
pointLayer = new OpenLayers.Layer.Vector("Point Layer");
map.addLayer(pointLayer);
drawPoint = new OpenLayers.Control.DrawFeature(pointLayer,OpenLayers.Handler.Point);
map.addControl(drawPoint);
drawPoint.activate();
//监听 featureadded 事件,当添加要素时会触发此事件
drawPoint.events.on({"featureadded": drawCompleted});
}
//定义 drawCompleted 函数,触发 click 事件会调用此函数
//事件参数 eventArgs 包含了绘制的要素 feature 信息 {feature: featureObj}
function drawCompleted(eventArgs) {
// 获取传入参数 eventArgs 的几何信息
var geometry = eventArgs.feature.geometry;
/* geometry = new OpenLayers.Geometry.Point(129,30);
geometry.transform(
new OpenLayers.Projection('EPSG:4326'),
new OpenLayers.Projection('EPSG:900913')
); */
//alert(geometry.x+","+geometry.y);
drawPoint.deactivate();
addmarker(new OpenLayers.LonLat(geometry.x,geometry.y));
pointLayer.destroy();
}
function addmarker(p) {
markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
size = new OpenLayers.Size(21, 25);
calculateOffset = function(size) {
return new OpenLayers.Pixel(-(size.w/2), -size.h); };
var icon = new OpenLayers.Icon(
'../imgs/1.jpg',
size, null, calculateOffset);
var make=new OpenLayers.Marker(p, icon)
markers.addMarker(make);
//markers.addMarker(new OpenLayers.Marker(p,icon.clone()));
var popup = new OpenLayers.Popup.FramedCloud("Popup",
p, null,
'<a target="_blank" href="http://openlayers.org/">We</a> ' +
'could be here.<br>Or elsewhere.', null,
true // <-- true if we want a close (X) button, false otherwise
);
map.addPopup(popup);
}
</script>
</head>
<body onload="init()">
<div id="tools">
<button id="PointDraw" onclick="PD()" value="on">画点</button>
</div>
<div id="map" style="width: 100%; height: 100%;"></div> ![代码效果图]
<img src="https://img-blog.csdn.net/20170718160834264?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzgxMjIxNzc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" ></img>
</body>
</html>
转载自:https://blog.csdn.net/qq_38122177/article/details/75307368