前面有过一篇文章讲过百度地图生成器的强大,但是那种只适合‘死数据’的定位,不能根据用户的注册信息进而动态定位,现在回顾项目分享给大家我的动态顶图定位实现方法。
一、HTML+JavaScript:
<div class="userPosition">
<div class="lframe" id="position">
<div class="tl"></div>
<div class="tr"></div>
<div class="tm">
<span class="tt"><a href="#" οnclick="search();return false;">点击获取TA的位置</a> </span>
</div>
<div class="wrapper">
<div class="ml"></div>
<div class="mr"></div>
<div class="mm" style="height: 380px;">
<div style="width: 644px; height: 386px; border: 1px solid gray" id="container"></div>
<div id="info"></div>
<div style="background: green;" id="info2"></div>
//百度地图api的开发密钥
<script type="text/javascript" src="http://api.map.baidu.com/api?key=46ce9d0614bf7aefe0ba562f8cf87194&v=1.0&services=true"></script>
<script type="text/javascript">
var map = new BMap.Map("container"); //创建地图实例
var point = new BMap.Point(120, 40); //创建点坐标,经度和纬度
map.centerAndZoom(point, 16); // 地图初始化
map.addControl(new BMap.NavigationControl()); //将标准地图控件添加到地图中 很明显 在左上角
map.addControl(new BMap.ScaleControl()); //一个比例尺控件 在左下角有一个500米
map.addControl(new BMap.OverviewMapControl()); //一个缩略图控件 在右下角箭头处
// 编写自定义函数,创建标注
function addMarker(point, index) {
var marker = new BMap.Marker(point, { icon: myIcon });
map.addOverlay(marker);
}
function search() {
var city = "<%=city%>";
var loc = "<%=country%>";
// 创建地址解析器实例
var myGeo = new BMap.Geocoder();
myGeo.getPoint(loc, function (point) {
if (point) {
map.centerAndZoom(point, 16);
map.addOverlay(new BMap.Marker(point));
}
}, city);
}
window.onload =function() {search()};
map.enableScrollWheelZoom();
map.enableContinuousZoom();
</script>
</div>
</div>
<div class="bl"></div>
<div class="br"></div>
<div class="bm"></div>
</div>
注意 :通过"<%=%>";这是一种前台JS获取后台数据的一种方式,在后台声明public,前台通过这种方式就可以直 接获取到了。
var city = "<%=city%>";
var loc = "<%=country%>";
二、后台C#代码:
主要是从数据库获取注册用户的家庭住址,如果没有填写家庭地址,自动定位到北京天安门广场
string needID = Request.QueryString["UserID"];
DataTable dthometown = new userInfoBLL().NeedHelpUserSapceByID(needID).Tables[0];
if (dthometown.Rows.Count == 0)
{
city = "北京";
country = "天安门广场";
}
else
{
//判断城市是否为空,如果为空,默认为廊坊
if (dthometown.Rows[0][18] == null || dthometown.Rows[0][19] == null || (dthometown.Rows[0][18].ToString()).Trim()=="")
{
city = "北京";
country = "天安门广场";
}
else
{
city = (dthometown.Rows[0][18].ToString()).Trim();
country = (dthometown.Rows[0][19].ToString()).Trim();
}
}
三、实现效果: