xh晓翰  
一、HTML结构
<div tabindex="-1" class="modal fade in active modal-map" role="dialog"> <div class="modal-dialog modal-md" aria-hidden="true" id="modal_sel_attend_overtime"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" title="关闭" ng-click="mapFun.hideMapOper()" data-dismiss="modal" aria-label="Close"> × </button> <h3 class="modal-title text-center" ng-bind="locationMap.lzMapTitle"></h3> </div> <div class="modal-body map-outwrap"> <div class="form-control form-control-viewicon map-input"> <i class="pull-right lzicon-map-line"></i> <input type="text" placeholder="输入关键字选取地点" id="pickerInput" class="form-control-noborder" /> <div id="message" class="message"></div> </div> <div id="maplocation-container" class="map-container" tabindex="0"></div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" ng-click="mapFun.hideMapOper()">取消</button> <button type="button" class="btn btn-primary" ng-click="mapFun.Addlocations()">确定</button> </div> </div> </div> </div>

  

二、指令逻辑

(function (window, angular, undefined) {

  var lzcontrolextended = angular.module('lz.controlextended', ['ng']);
/*======================web地图定位========================*/
 *eg:<div lz-Map-Location lz-location-data="attenVar.maplocation" 
* lz-callback-mapdata="attOperFun.callBackMapdata(data)></div> *{
longitude:""//地点经度
latitude:"",//地点纬度
lname:"",//地址名称
address:"",//详细地址名称
}
* callback-mapdata// 是编辑状态是返回的地图数据
*/ lzcontrolextended.directive("lzMapLocation", function ($modal, $timeout) { return {
            restrict: 'AE',
            replace: true,
            scope: {
                locationData: "=lzLocationData",
                lzCallbackMapdata: "&lzCallbackMapdata",
                lzMapTitle: "@lzMapTitle",
            },
            template: function (elem, attr) {
                var tmp = $(elem.context.outerHTML);
                tmp.attr("ng-click", "showMapOPer()");
                tmp.removeAttr("lz-map-location").removeAttr("lz-callback-mapdata").removeAttr("lzMapTitle");
                return tmp[0].outerHTML;
            },
            controller: function ($scope, $element) {

                $scope.locationMap = {
                    geocoder: "",
                    map: "",
                    markerFirst: [],
                    lzMapTitle: 
$scope.lzMapTitle == "" || $scope.lzMapTitle == undefined ? $scope.lzMapTitle = "位置" : $scope.lzMapTitle, loadJsFile: [//地图加载所需的JS "https://webapi.amap.com/maps?v=1.4.0&key=987ff0e3b1c29e9ee007a6c2abb1989a&plugin=AMap.DistrictSearch", "https://webapi.amap.com/demos/js/liteToolbar.js", "https://cache.amap.com/lbs/static/addToolbar.js" ] } //显示弹窗 $scope.showMapOPer = function () { $scope.mapOper = $modal({ scope: $scope, placement: "left", templateUrl: $versionManger.getHtml('/Base/PC/View/CommonComtrol/lzMapPosition.html'), backdrop: "static", prefixEvent: 'modal', show: false }); //加载js app.asyncjs($scope.locationMap.loadJsFile, function (data) { //需要在页面有了地图容器之后再去加载JS 这里使用了一个延时 $timeout(function () {
//深拷贝一份数据,在编辑时数据做了修改 不会影响原有数据 $scope.copyData = $scope.deepCopy($scope.locationData);
//当前页面是新建一个位置信息 $scope.mapState = "add"; if ($scope.copyData == null || $scope.copyData == undefined || $scope.copyData == "") { $scope.copyData = { address: "", lname: "", longitude: "",//地点经度 latitude: "",//地点纬度 proadcode: "",//省 cityadcode: "",//市 districtadcode: "",//县 } } else { if ($scope.copyData.address && $scope.copyData.longitude && $scope.copyData.latitude) { $scope.mapState = "edit"; } } //初始化地图的内容 if ($scope.copyData.longitude == "" || $scope.copyData.longitude == undefined && $scope.copyData.latitude == "" || $scope.copyData.latitude == undefined) { $scope.copyData.longitude = 116.397477; $scope.copyData.latitude = 39.908692; } $scope.locationMap.map = new AMap.Map('maplocation-container', { resizeEnable: true, zoom: 11, center: [$scope.copyData.longitude, $scope.copyData.latitude] }); //加载地图数据(搜索框联想输入,地理定位及所属城市adcode查询) AMap.plugin(["AMap.Autocomplete", "AMap.Geocoder", "AMap.DistrictSearch"], function () { var opts = { subdistrict: 1, //返回下一级行政区 showbiz: false //最后一级返回街道信息 }; //获取adcode var district = new AMap.DistrictSearch(opts); //城市,默认:“全国” var geocoder = new AMap.Geocoder({ city: "北京", radius: 1000, }); var autoOptions = { input: "pickerInput" //使用联想输入的input的id }; //销毁联想输入下拉框 if ($(".amap-sug-result").length > 0) { $(".amap-sug-result").remove(); } var autocomplete = new AMap.Autocomplete(autoOptions); //设置下拉框的z-indx 项目需求 $(".amap-sug-result").css("z-index", "1050"); //监听输入框输入地址功能 AMap.event.addListener(autocomplete, "select", function (e) { if ($scope.locationMap.markerFirst.length != 0) { $scope.locationMap.markerFirst.setMap(); } $scope.$apply(function () { $scope.copyData.address = e.poi.district + e.poi.name; $scope.copyData.lname = e.poi.name; $scope.copyData.longitude = e.poi.location.lng;//地点经度 $scope.copyData.latitude = e.poi.location.lat;//地点纬度 }); if (e.poi.location) { $scope.locationMap.markerFirst.setPosition(e.poi.location); $scope.locationMap.map.setCenter($scope.locationMap.markerFirst.getPosition()); $scope.locationMap.markerFirst.setMap($scope.locationMap.map); } else { $scope.locationMap.map.setCity(e.poi.adcode); } message.innerHTML = ""; });
AMAP.event.addListener(geocoder,"complete",function(data){
var adComInfo=data.regeocode.addressComponent;
if (adComInfo.province) {
                                        district.search(adComInfo.province, function (status, result) {
                                            if (status == 'complete') {
                                                $scope.copyData.proadcode = result.districtList[0].adcode;
                                            }
                                        });
                                    }
//所在市的adcode if (adComInfo.city) { district.search(adComInfo.city, function (status, result) { if (status == 'complete') { $scope.copyData.cityadcode = result.districtList[0].adcode } }); }
//所在县的adcode if (adComInfo.district) { district.search(adComInfo.district, function (status, result) { if (status == 'complete') { $scope.copyData.districtadcode = result.districtList[0].adcode } }); } }); //加载工具条(放大缩小地图) AMap.plugin(['AMap.ToolBar'], function () { var tool = new AMap.ToolBar(); $scope.locationMap.map.addControl(tool); }); if ($scope.locationMap.markerFirst.length == 0) { $scope.locationMap.markerFirst = new AMap.Marker({ map: $scope.locationMap.map, bubble: true }); } $scope.locationMap.markerFirst.setMap(); var input = document.getElementById("pickerInput"); var message = document.getElementById("message"); //地图点击 $scope.locationMap.map.on("click", function (e) { if ($scope.locationMap.markerFirst.length != 0) { $scope.locationMap.markerFirst.setMap(); } $scope.locationMap.markerFirst.setPosition(e.lnglat); $scope.locationMap.map.setCenter([e.lnglat.lng, e.lnglat.lat]); $scope.locationMap.markerFirst.setMap($scope.locationMap.map); geocoder.getAddress(e.lnglat, function (status, result) { if (status == "complete" && result.info === 'OK') { $scope.$apply(function () { $scope.callchange(e, result); message.innerHTML = ""; }) } else { message.innerHTML = "无法获取地址"; } }); }); }); //是新增状态 if ($scope.mapState == "add") { $("#pickerInput").val(""); $scope.copyData = { address: "", lname: "", longitude: "",//地点经度 latitude: "",//地点纬度 proadcode: "", cityadcode: "", districtadcode: "", } //定位当前位置 $scope.locationMap.map.plugin('AMap.Geolocation', function () { var geolocation = new AMap.Geolocation({ enableHighAccuracy: true,//是否使用高精度定位,默认:true timeout: 10000, //超过10秒后停止定位,默认:无穷大 maximumAge: 0, //定位结果缓存0毫秒,默认:0 convert: true, //自动偏移坐标,偏移后的坐标为高德坐标,默认:true showButton: true, //显示定位按钮,默认:true buttonPosition: 'LB', //定位按钮停靠位置,默认:'LB',左下角 buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20) showMarker: true, //定位成功后在定位到的位置显示点标记,默认:true showCircle: true, //定位成功后用圆圈表示定位精度范围,默认:true panToLocation: true, //定位成功后将定位到的位置作为地图中心点,默认:true zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false }); $scope.locationMap.map.addControl(geolocation); geolocation.getCurrentPosition(); AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息 AMap.event.addListener(geolocation, 'error', onError); //返回定位出错信息 }); //解析定位结果 function onComplete(data) { var lng = data.position.getLng(); var lat = data.position.getLat(); if ($scope.locationMap.markerFirst == 0) { $scope.locationMap.markerFirst = new AMap.Marker({ map: $scope.locationMap.map, bubble: true, position: [lng, lat], }); } else { $scope.locationMap.markerFirst.position = [lng, lat]; } $scope.locationMap.map.setCenter([lng, lat]); } function onError(obj) { console.log(obj.message); } } else { //地图编辑状态 if ($scope.mapState == "edit") { if ($scope.copyData && $scope.copyData != "" && typeof ($scope.copyData) != "object" && typeof ($scope.copyData) === "string") { $scope.copyData = JSON.parse($scope.copyData); } $("#pickerInput").val($scope.copyData.address); if (!$scope.locationMap.markerFirst.length != 0) { $scope.locationMap.markerFirst = new AMap.Marker({ map: $scope.locationMap.map, bubble: true, position: [$scope.copyData.longitude, $scope.copyData.latitude], }); } else { $scope.locationMap.markerFirst.position = [$scope.copyData.longitude, $scope.copyData.latitude]; } $scope.locationMap.map.setCenter([$scope.copyData.longitude, $scope.copyData.latitude]); } } $scope.callchange = function (e, result) { $scope.copyData = { lname: result.regeocode.addressComponent.street + result.regeocode.addressComponent.streetNumber + result.regeocode.addressComponent.township, address: result.regeocode.formattedAddress, latitude: e.lnglat.lat, longitude: e.lnglat.lng, proadcode: "", cityadcode: "", districtadcode: "", } $("#pickerInput").val($scope.copyData.address); } }, 500); }); //显示弹窗 $scope.mapOper.$promise.then($scope.mapOper.show); }; //关闭弹窗 $scope.mapFun = { hideMapOper: function () { $scope.mapOper.destroy(); }, //确定(选择好位置信息之后 给页面抛出信息) Addlocations: function () { if ($("#pickerInput").val() == "") { $scope.copyData = { longitude: "", latitude: "", address: "", lname: "", proadcode: "", cityadcode: "", districtadcode: "", } } else { if ($scope.copyData.address == "" && $("#pickerInput").val() != $scope.copyData.address) { opacityAlert("当前地址无效,请重新选择!", "glyphicon glyphicon-info-sign"); return false; } } $scope.locationData.address = $scope.copyData.address; $scope.locationData.lname = $scope.copyData.lname; $scope.locationData.longitude = $scope.copyData.longitude; $scope.locationData.latitude = $scope.copyData.latitude; $scope.locationData.proadcode = $scope.copyData.proadcode;//省编码 $scope.locationData.cityadcode = $scope.copyData.cityadcode;//城市编码 $scope.locationData.districtadcode = $scope.copyData.districtadcode;//县编码 if (typeof $scope.lzCallbackMapdata == "function") { $scope.lzCallbackMapdata({ data: $scope.locationData }); } $scope.mapOper.destroy(); } } //深克隆 $scope.deepCopy = function (obj) { var o; if (typeof obj == "object") { if (obj === null) { o = null; } else { if (obj instanceof Array) { o = []; for (var i = 0, len = obj.length; i < len; i++) { o.push($scope.deepCopy(obj[i])); } } else { o = {}; for (var j in obj) { o[j] = $scope.deepCopy(obj[j]); } } } } else { o = obj; } return o; }; }, } }); })(window, angular, undefined);

  

 三、指令使用

1.页面元素使用指令
<button type="button" class="btn btn-sm btn-link"
lz-map-location lz-location-data="maplocation" lz-callback-mapdata="attOperFun.callBackMapdata(data)" lz-map-title="设置考勤地点"> 编辑</button>
2.JS
//初始化数据源
$scope.maplocation:{
longitude:"",
latitude:"",
lname:"",
address:"",
proadcode: "",//省
cityadcode: "",//市
districtadcode: "",//县
 //编辑处理地图逻辑回调
callBackMapdata: function (data) {
 if ((data.address == "")
     && (data.latitude == "")
     && (data.lname == "")
     && (data.longitude == "")) {
      return false;
      }
  if ($scope.attOperVar.LocationModelStatus == 'add') {
     var mapData = {
        address: data.address,
        agid: "",
        alid: "",
        createtime: "",
        isdelete: "",
        latitude: data.latitude,
        lname: data.lname,
        longitude: data.longitude,
        oeid: "",
        };
      $scope.saveAttend.clocklocationlist.push(mapData);
       $scope.attOperVar.maplocation = {
               longitude: "",
               latitude: "",
               lname: "",
               address: "",
              }
            } else {
                if (data.address && data.lname) {
                    var item = $scope.saveAttend.clocklocationlist[$scope.attOperVar.LocationModelIndex];
                    item.longitude = data.longitude;
                    item.latitude = data.latitude;
                    item.lname = data.lname;
                    item.address = data.address;
                } else {
                    $scope.saveAttend.clocklocationlist.splice($scope.attOperVar.LocationModelIndex, 1);
                    return false;
                }
                $scope.attOperVar.isShowAttendLocation = false;
            }
        }
    };
}

 

posted on 2018-11-13 15:20  xh晓翰  阅读(250)  评论(0)    收藏  举报