地图封装,页面直接使用

百度地图
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.5&ak=YdpDlI7MXOf9zn2jGAYamWeWYNf6XQqN"></script>
 ((window) =>{
     var BaiduMap = function (map, allStores, allMarkers, resultStores, resultMarkers) {
          if (this instanceof BaiduMap) {
              this.map = map;
              this.allStores = allStores;
              this.allMarkers = allMarkers;
              this.resultStores = resultStores;
              this.resultMarkers = resultMarkers;
              this.initCity = function () {
                  addressInit('province', 'city', 'district', '北京', '', '海淀区');
              }();
              this.eventBind().initMap();
          } else {
              new BaiduMap(map, allStores, allMarkers, resultStores, resultMarkers);
          }
      };

      BaiduMap.prototype.eventBind = function() {
          var _this = this;
          //三级联动查询门店
          $("#district").change(function () {
              var province = $("#province").val();
              var district = $("#district").val().substring(0, 2);
              var city = $("#city").val().substring(0, 2);
              _this.initMap('http://aris.xin.cebest.com:80/customformsubmit/search', {
                  "formId": "d7d6d1260ca44277a10d1755cc451ff4", /*  d7d6d1260ca44277a10d1755cc451ff4 */
                  "showCount": 1000,//每页显示条数
                  "condition": province
              });
          });

          //按钮门店查询
          $('#mapSearch').on('click', function () {
              var queryName = $("#queryName").val().substring(0, 2);
              _this.initMap('http://aris.xin.cebest.com:80/customformsubmit/search', {
                  "formId": "d7d6d1260ca44277a10d1755cc451ff4", /*  d7d6d1260ca44277a10d1755cc451ff4 */
                  "showCount": 1000,//每页显示条数
                  "condition": queryName
              });
          });
          return this;
      };
      BaiduMap.prototype.initMap = function (url, data) {
          var _this = this;
          _this.map = new BMap.Map("map_canvas"); // 创建Map实例
          _this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 6); // 初始化地图,设置中心点坐标和地图级别
          //添加地图类型控件
          _this.map.addControl(new BMap.NavigationControl({
              anchor: BMAP_ANCHOR_TOP_RIGHT
          }));
          _this.map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
          _this.map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
          url = url || 'http://aris.xin.cebest.com:80/form/list';
          data = data || {
              "formId": "d7d6d1260ca44277a10d1755cc451ff4", /*  d7d6d1260ca44277a10d1755cc451ff4 */
              "showCount": 1000//每页显示条数
          };
          var stores = [];
          var marker = []; //地图标记
          $.ajax({
              url: url,
              type: "Post",
              dataType: "json",
              data: data,
              success: function (data) {
                  if (data.data == null) {
                      return false;
                  }
                  if (data.data.recordData != null) {
                      $.each(data.data.recordData, function (index, obj) {
                          var cur = {};
                          if (this[4].name == null || this[4].name == '' || this[4].name == undefined) {

                          } else {
                              var p0 = this[4].name.split(",")[1] / 1;
                              var p1 = this[4].name.split(",")[0] / 1;
                              var brandname = obj[2].name.replace(/\s/g, "");//去掉所有空格
                              cur.address = obj[3].name;
                              cur.contact = '/';
                              cur.name = obj[3].name + "店地址:" + obj[2].name;
                              cur.opentime = obj[1].creatTime.toString();
                              cur.location = {
                                  xAxis: p0,
                                  yAxis: p1,
                                  brandType: brandname
                              };
                              stores.push(cur);
                          }
                      });

                      _this.map.clearOverlays();
                      _this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 6);
                      _this.allStores = stores;
                      for (var i = 0; i < stores.length; i++) {
                          //店铺标注
                          if (stores[i].location != null && stores[i].location != '') {
                              var point = new BMap.Point(stores[i].location.yAxis, stores[i].location.xAxis);
                              var typeName = stores[i].location.brandType;
                              marker[i] = new BMap.Marker(point); // 创建标注
                              _this.map.addOverlay(marker[i]);
                              _this.showInfomessage(marker[i], i); //调用显示信息窗口的函数
                          }
                      }
                      //左侧列表点击事件
                      $('.store-info .detail div').each(function (e) {
                          $(this).on('click', function () {
                              var infoWindow = new BMap.InfoWindow(
                                  '<p class="name fnt_16 bold">' + stores[e].name + '</p>' +
                                  '<p class="location fnt_14">' + stores[e].address + '</p>' +
                                  '<p class="opentime fnt_14">' + stores[e].opentime + '</p>');
                              marker[e].openInfoWindow(infoWindow);
                              map.centerAndZoom(marker[e].getPosition, 16); // 初始化地图,设置中心点坐标和地图级别
                              _this.map.centerAndZoom(marker[e].getPosition(), 17);
                          })
                      });
                      $('.search-type a').each(function (e) {
                          $(this).on('click', function () {
                              $(this).addClass('actived');
                              $(this).siblings().removeClass('actived');
                              if (e == 0) {
                                  $('.search .search-keyword').show();
                                  $('.search .search-nearby').hide();
                              } else {
                                  $('.search .search-keyword').hide();
                                  $('.search .search-nearby').show();
                              }
                          })
                      });
                  }
                  _this.checkSearchDetail(stores);
              }
          });
          return this;
      };
      BaiduMap.prototype.storeMarker = function (stores, markers) {
          for (var i = 0; i < stores.length; i++) {
              //店铺标注
              if (stores[i].location != null && stores[i].location != '') {
                  var point = new BMap.Point(stores[i].location.xAxis, stores[i].location.yAxis);
                  markers[i] = new BMap.Marker(point); // 创建标注
                  this.map.addOverlay(markers[i]);
                  this.showInfomessage(markers[i], i); //调用显示信息窗口的函数
              }
          }
      };
      /*
       *
       * 所有的marker位置上显示infowindow
       */
      BaiduMap.prototype.showInfomessage = function (marker, index) {
          var _this = this;
          marker.addEventListener("click", function (e) {
              var infoWindow = new BMap.InfoWindow(
                  '<p class="name fnt_16 bold">' + _this.allStores[index].name + '</p>' +
                  '<p class="location fnt_14">' + _this.allStores[index].address + '</p>'
              );
              marker.openInfoWindow(infoWindow);
          });
      };

      BaiduMap.prototype.searchStore = function () {
          var _this = this;
          _this.resultStores.splice(0, _this.resultStores.length);

          this.resultStores[0] = {
              name: '宫廷壹号杭州旗舰店',
              address: '杭州滨江大都会第六空间瑞弗国际',
              opentime: '周一至周日 09:00~22:00',
              contact: '冯国根 13858129878',
              location: {
                  xAxis: 120.199415,
                  yAxis: 30.202633
              }
          };

          $('.store-info .detail').empty();

          for (var i = 0; i < _this.resultStores.length; i++) {

              // 搜索到结果店铺渲染
              $('.store-info .detail').append(
                  '<div class="store">' +
                  '<p class="name fnt_14 bold">' + _this.resultStores[i].name + '</p>' +
                  '<p class="location fnt_12">' + _this.resultStores[i].address + '</p>' +
                  '<p class="opentime fnt_12">' + _this.resultStores[i].opentime + '</p>' +
                  '<p class="contact fnt_12">' + _this.resultStores[i].contact + '</p>' +
                  '</div>'
              )
          }
          map.clearOverlays();
          storeMarker(_this.resultStores, _this.resultMarkers);
          this.checkSearchDetail();
      };
      BaiduMap.prototype.checkSearchDetail = function (arr) {
          if (arr.length <= 0) {
              $('.detail').hide();
          } else {
              $('.detail').show();
              $('.noMessage').hide();
          }
      };

      window.BaiduMap = BaiduMap;
      BaiduMap();;
 }(window))
      
复制代码
谷歌地图
<script type="text/javascript" src="http://maps.google.cn/maps/api/js?sensor=false&language=en&key=AIzaSyAyXwq79dCk3XgeYR0eu8B6PzoCdA_jP3k"></script>
    var GoolMap = function (geocoder, map,infoWindow, mapData, datas ) {
        this.geocoder = geocoder;
        this.map = map;
        this.browserSupportFlag =  new Boolean();
        this.infoWindow = infoWindow;
        this.mapData = mapData || [];
        this.datas = datas || [];
        this.searchInit = function () {
            addressInit('province', 'city', 'district', '北京', '', '海淀区');
        }();

        this.geocoder  = new google.maps.Geocoder();
        var myOptions = {
            zoom: 10, //区域 深度
            //mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        this.map  = new google.maps.Map(document.getElementById("map_canvas"), myOptions); //创建地图
    };

    GoolMap.prototype.init = function () {
        var _this = this;
        $.ajax({
            url: 'http://www.chinaaris.com:80/form/list',
            type: 'POST',
            data: {
                "formId": "d7d6d1260ca44277a10d1755cc451ff4", /*  d7d6d1260ca44277a10d1755cc451ff4 */
                "showCount": 1000//每页显示条数
            },
            dataType: "json",
            success: function (data) {
                if (data.data == null) {
                    return false;
                }
                var num = data.data.recordData.length;
                $(data.data.recordData).each(function (i) {
                    var addres = {};
                    if (this[4].name == null || this[4].name == '' || this[4].name == undefined) {
                    } else {
                        addres.description = "<h3>" + this[1].name + "店</h3>地址:" + this[3].name;
                        addres.latlng = new google.maps.LatLng(this[4].name.split(",")[1] / 1, this[4].name.split(",")[0] / 1);
                        addres.longitude = this[4].name.split(",")[1] / 1;
                        addres.latitude = this[4].name.split(",")[0] / 1;
                        addres.seq = "";
                        addres.area = "";
                        addres.nationFlag = "";
                        addres.marker = null;
                        addres.visible = true;
                        addres.mapType = "";
                        addres.tempdescription = "";
                        _this.datas.push(addres);
                    }
                });
                _this.initialize();
            }
        });
    };

    GoolMap.prototype.attachMarkerClick = function(item){
        //console.log(item);

        try {
            var _this = this;
            google.maps.event.addListener(_this.mapData[item].marker, "click", function () {

                _this.infoWindow.setContent(_this.mapData[item].description);
                var defaultMapPos = new google.maps.LatLng(_this.mapData[item].latitude, _this.mapData[item].longitude);
                //console.log(defaultMapPos)
                _this.map.panTo(defaultMapPos);
                _this.map.setZoom(15);
                _this.infoWindow.open(_this.map, _this.mapData[item].marker);
                _this.map.setCenter(_this.mapData[item].marker.getPosition());
            });
        } catch (e) {
        }
    };
    GoolMap.prototype.initialize = function() {


        // var map = new google.maps.Map(document.getElementById("map_canvas"), {
        //     center: new google.maps.LatLng(47.61679190,-122.20208340),
        //     zoom: 10,
        //     //mapTypeId: google.maps.MapTypeId.ROADMAP
        // });

        // return;
        try {
             var _this = this;

                //控制地图的缩放级别
            google.maps.event.addListener(_this.map, 'zoom_changed', function () {
                if (_this.map.getZoom() < 2) _this.map.setZoom(2);
            });
            var myHtml = "";
            _this.infoWindow = new google.maps.InfoWindow({
                "maxWidth": 500,
                content: myHtml
            });
            _this.infoWindow.setContent(myHtml);

            _this.mapData = new Array();
            _this.mapData = _this.datas;
            console.log(_this.datas);
            for (var n = 0; n < _this.datas.length; n++) {
                (function (n) {
                    //console.log(mapData,n);
                    _this.mapData[n].marker = new google.maps.Marker({
                        map: _this.map,
                        visible: _this.mapData[n].visible,
                        position: _this.mapData[n].latlng /*,icon:icon_file*/
                    });
                    _this.mapData[n].marker.setTitle(_this.mapData[n].title);
                    _this.attachMarkerClick(n);
                })(n);
            }
            var liCounts = 0;
            for (var i = 0; i <_this.mapData.length; i++) {
                liCounts++;
                _this.map.panTo(_this.mapData[i].latlng);
                _this.map.setZoom(6);
                _this.mapData[i].marker.setMap(_this.map);
            }
        } catch (e) {
        }
    };
    GoolMap.prototype.changeMap = function() {
        var _this = this;
        _this.datas = [];
        var province = $("#province").val();
        var district = $("#district").val().substring(0, 2);
        var city = $("#city").val().substring(0, 2);



        $.ajax({
            url: 'http://www.chinaaris.com:80/customformsubmit/search',
            type: 'POST',
            data: {
                "formId": "d7d6d1260ca44277a10d1755cc451ff4", /*  d7d6d1260ca44277a10d1755cc451ff4 */
                "showCount": 1000,//每页显示条数
                "condition": province
            },
            dataType: "json",
            success: function (data) {

                if (data.data == null || data.data.recordData == null) {
                    layer.msg('没有查询到任何店铺');
                    return false;
                }
                $(data.data.recordData).each(function (i) {
                    var addres = {};
                    if (this[4].name == null || this[4].name == '' || this[4].name == undefined) {
                    } else {
                        addres.description = "<h3>" + this[1].name + "店</h3>地址:" + this[3].name;
                        addres.latlng = new google.maps.LatLng(this[4].name.split(",")[1] / 1, this[4].name.split(",")[0] / 1);
                        addres.longitude = this[4].name.split(",")[1] / 1;
                        addres.latitude = this[4].name.split(",")[0] / 1;
                        addres.seq = "";
                        addres.area = "";
                        addres.nationFlag = "";
                        addres.marker = null;
                        addres.visible = true;
                        addres.mapType = "";
                        addres.tempdescription = "";
                        if (this[3].name.match(district)) {
                            _this.datas.push(addres);
                        }
                    }
                });
                if (_this.datas.length == 0) {
                    layer.msg('没有查询到任何店铺!');
                    return;
                }

                _this.initialize();
            }
        });
    };
            $('#mapSearch').on('click', function () {
            var district = $("#queryName").val().substring(0, 2);
            if (goolMap.mapData != null) {
                for (var i = 0; i < goolMap.mapData.length; i++) {
                    goolMap.mapData[i].marker.setMap(null);
                }
            }
            goolMap.changeMap(district);
        });

        $("#district").change(function () {
            goolMap.changeMap();
            if (goolMap.mapData != null) {
                for (var i = 0; i < goolMap.mapData.length; i++) {
                    goolMap.mapData[i].marker.setMap(null);
                }
            }
        });
        goolMap.init();复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个常见的前端开发需求。我推荐使用 Vue.js 框架和百度地图 JavaScript API 来实现。我们可以封装一个地图选择组件,组件包含一个按钮,点击按钮可以打开弹框,弹框中展示百度地图,并提供搜索和选择点位的功能。 首先,我们需要在页面中引入 Vue.js 和百度地图 JavaScript API,代码如下: ```html <!-- 引入 Vue.js --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- 引入百度地图 JavaScript API --> <script src="https://api.map.baidu.com/api?v=3.0&ak=您的密钥"></script> ``` 然后,我们可以创建一个地图选择组件,代码如下: ```html <template> <div> <button @click="openMap">选择位置</button> <div v-show="showMap"> <div ref="map" style="width: 100%; height: 500px;"></div> <input type="text" v-model="searchKeyword" placeholder="请输入地址"> <button @click="search">搜索</button> <ul> <li v-for="poi in pois" :key="poi.uid"> <a href="#" @click="selectPoi(poi)">{{poi.name}}</a> </li> </ul> <button @click="confirm">确定</button> <button @click="closeMap">取消</button> </div> <div v-if="selectedPoi"> <p>经度:{{selectedPoi.point.lng}}</p> <p>纬度:{{selectedPoi.point.lat}}</p> <p>地址:{{selectedPoi.name}}</p> </div> </div> </template> <script> export default { data() { return { showMap: false, map: null, searchKeyword: '', pois: [], selectedPoi: null } }, mounted() { // 创建地图实例 this.map = new BMap.Map(this.$refs.map) // 设置地图中心点 this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 11) // 启用滚轮缩放 this.map.enableScrollWheelZoom(true) }, methods: { openMap() { this.showMap = true }, closeMap() { this.showMap = false }, search() { const local = new BMap.LocalSearch(this.map, { onSearchComplete: (results) => { if (local.getStatus() === BMAP_STATUS_SUCCESS) { this.pois = results.map((result) => result.getPoi(0)) } } }) local.search(this.searchKeyword) }, selectPoi(poi) { this.selectedPoi = poi }, confirm() { this.$emit('selected', this.selectedPoi.point.lng, this.selectedPoi.point.lat, this.selectedPoi.name) this.showMap = false } } } </script> ``` 在这个组件中,我们使用了 Vue.js 的模板语法,定义了一个按钮和一个地图弹框。地图弹框中包含了一个地图容器、一个搜索框、一个搜索按钮、一个点位列表、一个确定按钮和一个取消按钮。 在组件的 JavaScript 部分,我们定义了一些数据,如是否显示地图弹框、地图实例、搜索关键词、搜索结果和选择的点位。在组件挂载后,我们创建了一个百度地图实例,并设置了地图的中心点和缩放级别。 在组件的方法部分,我们定义了一些操作。打开地图弹框时,我们将 showMap 数据设置为 true;关闭地图弹框时,我们将 showMap 数据设置为 false。在搜索时,我们使用百度地图的 LocalSearch 类进行地址搜索,并将搜索结果存储在 pois 数组中。选择点位时,我们将选中的 poi 存储在 selectedPoi 数据中。确定操作时,我们将选中的经纬度和中文名字通过 emit 事件传递给父组件,并关闭地图弹框。 最后,我们可以在父组件中使用地图选择组件,代码如下: ```html <template> <div> <map-select @selected="handleSelected"></map-select> </div> </template> <script> import MapSelect from './MapSelect.vue' export default { components: { MapSelect }, methods: { handleSelected(lng, lat, name) { alert(`经度:${lng},纬度:${lat},地址:${name}`) } } } </script> ``` 在这个父组件中,我们引入了地图选择组件,并通过 @selected 监听其选中事件。当选中事件触发时,我们弹出一个提示框,展示选中的经纬度和中文名字。 这样,我们就完成了一个基于 Vue.js 和百度地图地图选择组件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值