angularjs1 实现地图添加自定义控件(搜索功能)及事件

// 添加地图自定义控件的事件
function addEventHandler(target, eventName, handler) {
if (target.addEventListener) {
target.addEventListener(eventName, handler, false);
} else if (target.attachEvent) {
target.attachEvent("on" + eventName, handler);
} else {
target["on" + eventName] = handler;
}
}
//自定义地图上的搜索控件
function searchControl(){
// 设置默认停靠位置和偏移量
this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
this.defaultOffset = new BMap.Size(10, 10);

this.searchBox = document.createElement("input");// 搜索框
this.searchBox.setAttribute("type", "text");
this.searchButton = document.createElement("span");// 搜索按钮
}
searchControl.prototype = new BMap.Control();
searchControl.prototype.initialize = function(map){
// 创建一个DOM元素
var div = document.createElement("div");
// 设置样式
div.className = "hosmapsearch";
var self = this;
var searchInput = this.searchBox;
searchInput.className = "basictypefour";
searchInput.placeholder = "搜索...";
var searchBtn = this.searchButton;
searchBtn.className = "hopsearcon";

addEventHandler(searchBtn, "click", function() {
var address = searchInput.value;
// 创建地址解析器实例
var myGeo = new BMap.Geocoder();
// 将地址解析结果显示在地图上,并调整地图视野
myGeo.getPoint(address, function(point){
if (point) {
$scope.$apply(function(){
$scope.coordinate = JSON.stringify(point);
});
console.log($scope.coordinate);
map.centerAndZoom(point, 16);
map.addOverlay(new BMap.Marker(point));
}
}, address);
});
//添加输入框和搜索按钮到div中
div.appendChild(searchInput);
div.appendChild(searchBtn);
// 添加DOM元素到地图中
map.getContainer().appendChild(div);

// 将DOM元素返回
return div;
}

//初始化map
var map;
var initialize = {
initMap:function(){
map = new BMap.Map("hospitalAddMap"); // 创建Map实例
var point = new BMap.Point(39.919422,116.417773);//默认初始化地图中心点(BJ)
map.centerAndZoom(point,16);// 初始化地图,设置中心点坐标和地图级别
map.enableScrollWheelZoom(true);//开启鼠标滚轮缩放
map.enableDragging();//拖拽

// 创建控件实例
var mySearchCtrl = new searchControl();
// 添加到地图当中
map.addControl(mySearchCtrl);

this.setCityCenter();
},
setCityCenter:function(){
function myFun(result){//ip定位初始化城市
var cityName = result.name;
console.log(cityName);
map.centerAndZoom(cityName, 16);
}
var myCity = new BMap.LocalCity();
myCity.get(myFun);
}
}

//init map
initialize.initMap();

上一篇:js自执行函数注意事项


下一篇:Atitit 项目管理(5)----------后勤管理与工具链支持管理