当前位置:首页 > Windows程序 > 正文

C#百度地图

2021-03-22 Windows程序

最近单位一个项目要用到百度地图

功能非常简单

1.填写坐标,点击"在地图上搜索",显示地图,把地址带到另外一个文本框上

2.填写地址,点击"在地图上搜索",显示地图,把坐标带到另外一个文本框上

1.加入API库的链接

<script src="" type="text/javascript"></script>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.4">
</script>

2.在需要嵌入百度地图的位置加上div和js

<div></div>
<script type="text/javascript">
function InitMap() {
var valCoord = $("#txtCoordinate").val();//取坐标
if (valCoord == null) {
return;
}
var pointX = valCoord.split(‘,‘)[0];
var pointY = valCoord.split(‘,‘)[1];
var map = new BMap.Map("container"); //创建地图对象
map.centerAndZoom(new BMap.Point(pointX, pointY), 16); //初始化地图
var myGeo = new BMap.Geocoder();// 创建地理编码实例

if (valCoord != ‘请输入坐标‘ && valCoord != ‘‘) //优先取坐标去查询地图
{
// 根据坐标得到地址描述
myGeo.getLocation(new BMap.Point(pointX, pointY), function (result) {
if (result) {
$("#txtLocation").val(result.address);
map.addOverlay(new BMap.Marker(new BMap.Point(pointX, pointY)));
return;
}
});
}

if ($("#txtLocation").val() != ‘‘ && $("#txtLocation").val() != ‘请输入客户公司地址搜索在地图上的位置‘) //取地址去查询地图
{
// 将地址解析结果显示在地图上,并调整地图视野
myGeo.getPoint($("#txtLocation").val(), function (p) {
if (p) {
map.centerAndZoom(p, 16);
map.addOverlay(new BMap.Marker(p));
var valLngLat = p.lng + "," + p.lat;
$("#txtCoordinate").val(valLngLat);
return;
}
}, "上海");
}
}
InitMap();
</script>

3.文本框

<input type="text" value="请输入坐标" />

<textarea rows="1" cols="30">请输入客户公司地址搜索在地图上的位置</textarea>

4.为文本框绑定一些事件

<style type="text/css">
#container {
height: 100%;
width: 100%;
}
</style>
<script type="text/javascript">
$(function () {
$("#txtCoordinate").focus(function () {
if ($("#txtCoordinate").val() == "请输入坐标") {
$("#txtCoordinate").val("");
}
});
$("#txtCoordinate").focusout(function () {
if ($("#txtCoordinate").val() == "") {
$("#txtCoordinate").val("请输入坐标");
}
});
$("#txtLocation").focus(function () {
$("#txtCoordinate").val("");
if ($("#txtLocation").val() == "请输入客户公司地址搜索在地图上的位置") {
$("#txtLocation").val("");
}
});
});
</script>

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/65427.html