百度地图API (1):往地图中添加标注点

2 篇文章 0 订阅

自己项目中实践:

列表展示:

<head>
    <style type="text/css">
        #allmap {width: 600px;height: 400px;overflow: hidden;margin:0;}
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=40GWXiduhOft266lK4N1dopL"></script>
</head>
<body>
<table
    <tbody>
        <tr>
            <th class="center" style="vertical-align: middle">地址</th>
            <td style="vertical-align:top;" colspan="2">
                <input type="hidden" id="CMP_LOC" value="${var.CMP_LOC} ${var.CMP_NAME}" title="地址">
                <input type="hidden" id="LONGITUDE" value="${var.LONGITUDE}" title="经度">
                <input type="hidden" id="LATITUDE" value="${var.LATITUDE}"  title="纬度">
                <input type="hidden" id="PZOOM" value="${var.PZOOM}"  title="拉伸">
                <div id="allmap"></div>
            </td>
        </tr>
    </tbody>
</table>
<script type="text/javascript">
	// 百度地图API功能
	var map = new BMap.Map("allmap");
	map.enableScrollWheelZoom();    //启用滚轮放大缩小,默认禁用

	map.addControl(new BMap.ScaleControl());// 添加默认比例尺控件
	map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT}));// 左上
	map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_RIGHT}));// 右上
	map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT}));// 左下
	map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT}));// 右下

	map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
	map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}));  //右上角,仅包含平移和缩放按钮
	map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT, type: BMAP_NAVIGATION_CONTROL_PAN}));  //左下角,仅包含平移按钮
	map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_ZOOM}));  //右下角,仅包含缩放按钮

	//创建跳动的位置图标
	var point = new BMap.Point($("#LONGITUDE").val(), $("#LATITUDE").val());
	map.centerAndZoom(point, $("#PZOOM").val());
	var marker = new BMap.Marker(point);  // 创建标注
	map.addOverlay(marker);               // 将标注添加到地图中
	//添加监听事件
	(function() {
		marker.addEventListener('click',
				//显示信息的方法
				function() {
					showInfo(this,point);
				});
	})();
	marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
	function showInfo(thisMarker,point) {
		//获取点的信息
		var sContent = '<span style="width: 200px;display: inline-block;">'+$("#CMP_LOC").val()+'</span>';
		var infoWindow = new BMap.InfoWindow(sContent); //创建信息窗口对象
		thisMarker.openInfoWindow(infoWindow); //图片加载完后重绘infoWindow
	}
	</script>
</body>

页面编辑 地图选点:

<tr>
    <td style="width:79px;text-align: right;padding-top: 13px;">经度:</td>
    <td><input type="number" name="LONGITUDE" id="LONGITUDE" value="${pd.LONGITUDE }" maxlength="200" placeholder="这里输入经度" title="经度" style="width:98%;"/></td>
    <td rowspan="2" style="width:79px;vertical-align: middle;padding-right: 15px;">
        <a class="btn btn-app btn-light btn-xs"  onclick="openMap();"><i class="ace-icon fa fa-globe"></i>地图选点</a>
    </td>
</tr>
<tr>
    <td style="width:79px;text-align: right;padding-top: 13px;">纬度:</td>
    <td><input type="number" name="LATITUDE" id="LATITUDE" value="${pd.LATITUDE }" maxlength="200" placeholder="这里输入纬度" title="纬度" style="width:98%;"/></td>
</tr>

<script type="text/javascript">
    $(top.hangge());
    function openMap(){
        top.jzts();
    	var diag = new top.Dialog();
        diag.Drag=true;
        diag.Title ="地图";
        diag.URL ="<%=basePath%>cmpbase/mapXY.do";
        diag.Width = 700;
        diag.Height = 500;
        diag.CancelEvent = function(){ //关闭事件
            var LATITUDE  = diag.innerFrame.contentWindow.document.getElementById('ZUOBIAO_X').value;
            var LONGITUDE  = diag.innerFrame.contentWindow.document.getElementById('ZUOBIAO_Y').value;
            if(LATITUDE !='' && LONGITUDE != ''){
                document.getElementById("LATITUDE").value = LATITUDE;
                document.getElementById("LONGITUDE").value = LONGITUDE;
            }
            diag.close();
        };
        diag.show();
    }
</script>

后台:

/**获取地图坐标页面
 * @return
 * @throws Exception
 */
@RequestMapping(value="/mapXY")
public ModelAndView mapXY() throws Exception{
	ModelAndView mv = this.getModelAndView();
	PageData pd = new PageData();
	pd = this.getPageData();
	mv.setViewName("web/company/mapXY");
	mv.addObject("pd", pd);
	return mv;
}

跳转MapXY.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>选点获取经纬度</title>
    <base href="<%=basePath%>">
    <script type="text/javascript" src="static/js/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=40GWXiduhOft266lK4N1dopL"></script>

    <style type="text/css">
        body, html, #allmap {
            width: 100%;
            height: 100%;
            overflow: hidden;
            margin: 0;
        }

        #l-map {
            height: 100%;
            width: 78%;
            float: left;
            border-right: 2px solid #bcbcbc;
        }

        #r-result {
            height: 100%;
            width: 20%;
            float: left;
        }
    </style>

    <script type="text/javascript">
        $(top.hangge());
        var dg;
        $(document).ready(function () {
            dg = frameElement.lhgDG;
        });

        function success() {
            if (dg.curWin.document.forms[0]) {
                dg.curWin.document.forms[0].action = dg.curWin.location + "";
                dg.curWin.document.forms[0].submit();
            } else {
                dg.curWin.location.reload();
            }
            dg.cancel();
        }

        function choose() {
            var ZUOBIAO_X = document.getElementById("ZUOBIAO_X").value;
            var ZUOBIAO_Y = document.getElementById("ZUOBIAO_Y").value;
            if (ZUOBIAO_X == "" || ZUOBIAO_Y == "") {
                alert("请先输入经纬度");
            } else {
                top.Dialog.close();
            }
        }
    </script>
</head>
<body>
<div>
    <table bgcolor="#E3E4D8" width="100%">
        <tr>
            <td>纬度:</td>
            <td><input id="ZUOBIAO_X" value="" type="text"/></td>
            <td>经度:</td>
            <td><input id="ZUOBIAO_Y" value="" type="text"/></td>
            <td><input type="button" value="确定" onclick="choose();"/></td>
            <td width="100">
                <input type="text" id="suggestId" size="20" value="这里输入搜索地址" style="width:150px;"/>
            </td>
        </tr>
    </table>
</div>
<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto;">
    </td>
    </tr>
    </table>
</div>
<div id="allmap"></div>

</body>

</html>

<script type="text/javascript">
// 百度地图API功能
    function G(id) {
        return document.getElementById(id);
    }

    var map = new BMap.Map("allmap");
    map.centerAndZoom("北京", 12);                  	 	// 初始化地图,设置城市和地图级别。

    var ac = new BMap.Autocomplete(    					//建立一个自动完成的对象
        {
            "input": "suggestId"
            , "location": map
        });

    ac.addEventListener("onhighlight", function (e) {  	//鼠标放在下拉列表上的事件
        var str = "";
        var _value = e.fromitem.value;
        var value = "";
        if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

        value = "";
        if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
        //G("searchResultPanel").innerHTML = str;
    });

    var myValue;
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        //G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

        setPlace();
    });

    function setPlace() {
        map.clearOverlays();    //清除地图上所有覆盖物
        function myFun() {
            var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
            map.centerAndZoom(pp, 18);
            map.addOverlay(new BMap.Marker(pp));    		//添加标注
        }

        var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
        });
        local.search(myValue);
    }


    map.addControl(new BMap.ScaleControl());                    // 添加默认比例尺控件
    map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT}));                    // 左上
    map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_RIGHT}));                    // 右上
    map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT}));                    // 左下
    map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT}));                    // 右下

    map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
    map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}));  //右上角,仅包含平移和缩放按钮
    map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT, type: BMAP_NAVIGATION_CONTROL_PAN}));  //左下角,仅包含平移按钮
    map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_ZOOM}));  //右下角,仅包含缩放按钮

    map.enableScrollWheelZoom();    //启用滚轮放大缩小,默认禁用
    map.enableContinuousZoom();    	//启用地图惯性拖拽,默认禁用


    function showInfo(e) {

        document.getElementById("ZUOBIAO_X").value = e.point.lat;
        document.getElementById("ZUOBIAO_Y").value = e.point.lng;

    }

    map.addEventListener("click", showInfo);
</script>

结合网上资料:

使用过程中需要一些标注的描述 ,点击这里查看原文:

1.实现功能:通过给定的坐标点,往地图中添加标注点,点击标注点,显示改点的详细信息。
2.效果图:
演示链接:http://www.ltbetter.com:8080/BMap/MapTest1.html

这里写图片描述
3.核心方法:

  • 手动创建数据,实际项目则是接受GPS信息
//建立坐标点:
// lng:经度 lat:纬度
var points = [  
{"lng":112.58,"lat":26.89,"url":"http://www.baidu.com","id":1,"name":"p1"},  
{"lng":112.59,"lat":26.90,"url":"http://www.mi.com","id":2,"name":"p2"},  
{"lng":112.57,"lat":26.88,"url":"http://www.csdn.com","id":3,"name":"p3"}  
]; 
  • 创建添加标注点到地图,并为标注点添加点击事件
//创建标注点并添加到地图中
function addMarker(points) {
    //循环建立标注点
    for(var i=0, pointsLen = points.length; i<pointsLen; i++) {
        var point = new BMap.Point(points[i].lng, points[i].lat); //将标注点转化成地图上的点
        var marker = new BMap.Marker(point); //将点转化成标注点
        map.addOverlay(marker);  //将标注点添加到地图上
        //添加监听事件
        (function() {
            var thePoint = points[i];
            marker.addEventListener("click",
            //显示信息的方法
                function() {
                showInfo(this,thePoint);
            });
         })();  
    }
}
  • 编写信息显示方法
function showInfo(thisMarker,point) {
    //获取点的信息
    var sContent = 
    '<ul style="margin:0 0 5px 0;padding:0.2em 0">'  
    +'<li style="line-height: 26px;font-size: 15px;">'  
    +'<span style="width: 50px;display: inline-block;">id:</span>' + point.id + '</li>'  
    +'<li style="line-height: 26px;font-size: 15px;">'  
    +'<span style="width: 50px;display: inline-block;">名称:</span>' + point.name + '</li>'  
    +'<li style="line-height: 26px;font-size: 15px;"><span style="width: 50px;display: inline-block;">查看:</span><a href="'+point.url+'">详情</a></li>'  
    +'</ul>';
    var infoWindow = new BMap.InfoWindow(sContent); //创建信息窗口对象
    thisMarker.openInfoWindow(infoWindow); //图片加载完后重绘infoWindow
}
  • 创建地图
//创建地图
var map = new BMap.Map("allmap");    
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);  // 设置中心点
map.centerAndZoom( "衡阳");       //指定中心城市
map.setCurrentCity("衡阳");          
map.addControl(new BMap.MapTypeControl());  //设置可拖拽 
map.enableScrollWheelZoom(true);  //添加滚轮缩放   
addMarker(points); //添加标注
</script>
  • Tip: 想使用百度地图api需要申请一个ak,申请方法就不介绍了,百度一大堆.

完整代码(不包括api的ak 需要自己申请):

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
</style>
<script type="text/javascript" 
//ak填自己申请的ak
src="http://api.map.baidu.com/api?v=2.0& ak=你申请的AK">
</script>
<title>百度地图api展示</title>
</head>
<body>
<div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
//新建三个地图上点
var points = [  
{"lng":112.58,"lat":26.89,"url":"http://www.baidu.com","id":1,"name":"p1"},  
{"lng":112.59,"lat":26.90,"url":"http://www.mi.com","id":2,"name":"p2"},  
{"lng":112.57,"lat":26.88,"url":"http://www.csdn.com","id":3,"name":"p3"}  
]; 
//创建标注点并添加到地图中
function addMarker(points) {
    //循环建立标注点
    for(var i=0, pointsLen = points.length; i<pointsLen; i++) {
        var point = new BMap.Point(points[i].lng, points[i].lat); //将标注点转化成地图上的点
        var marker = new BMap.Marker(point); //将点转化成标注点
        map.addOverlay(marker);  //将标注点添加到地图上
        //添加监听事件
        (function() {
            var thePoint = points[i];
            marker.addEventListener("click",
                function() {
                showInfo(this,thePoint);
            });
         })();  
    }
}
function showInfo(thisMarker,point) {
    //获取点的信息
    var sContent = 
    '<ul style="margin:0 0 5px 0;padding:0.2em 0">'  
    +'<li style="line-height: 26px;font-size: 15px;">'  
    +'<span style="width: 50px;display: inline-block;">id:</span>' + point.id + '</li>'  
    +'<li style="line-height: 26px;font-size: 15px;">'  
    +'<span style="width: 50px;display: inline-block;">名称:</span>' + point.name + '</li>'  
    +'<li style="line-height: 26px;font-size: 15px;"><span style="width: 50px;display: inline-block;">查看:</span><a href="'+point.url+'">详情</a></li>'  
    +'</ul>';
    var infoWindow = new BMap.InfoWindow(sContent); //创建信息窗口对象
    thisMarker.openInfoWindow(infoWindow); //图片加载完后重绘infoWindow
}
//创建地图
var map = new BMap.Map("allmap");    
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);  // 设置中心点
map.centerAndZoom( "衡阳");
map.setCurrentCity("衡阳");          //设置为衡阳
map.addControl(new BMap.MapTypeControl());   
map.enableScrollWheelZoom(true);     
addMarker(points);
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值