Bootstrap

google地图--自定义标记以及点击事件

最近看到朋友正在用谷歌地图做定位项目,看到地图实现的效果比较炫酷,很是喜欢,就模仿学习其中常用的一些效果。

我们经常写的就是定位系统。点击marker标记弹出框。但是谷歌地图弹出的框可能和我们的设计图不符合,这时候我们就要认为修改设计图来实现效果。

1.谷歌地图的基本使用
实现效果
这里写图片描述
代码如下:

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
  <title>获取地图缩放级别</title>
  <style>
    body,
    html {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
</head>

<body>
  <div id="map" style="width:100%;height:100%"></div>
  <script src="./lib/jquery.min.js"></script>
  <script src="http://ditu.google.cn/maps/api/js?key=AIzaSyD4B4IuS7uIJvBMvgptrSBK_yaoF6rTJYE&language=EN"></script>
  <!-- 中国版 -->
  <!--正常版,需FQ  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBp"></script> -->
  <script>
    var mapType = google.maps.MapTypeId.ROADMAP;
    var lat = 39.915168, lng = 116.403875, zoom = 10;
    var mapOptions = {
      center: {
        lat: 52.38027,
        lng: -1.5637500000000273
      },
      zoom: 2,
      styles: [{
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": [{ "saturation": 36 }, { "color": "#000000" }, { "lightness": 40 }]
      }, { "featureType": "all", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "all", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 17 }, { "weight": 1.2 }] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 21 }] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 29 }, { "weight": 0.2 }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 18 }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "transit", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 19 }] }, { "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }]
    };
    var map = new google.maps.Map(document.getElementById("map"), mapOptions); //创建谷歌地图
    // var marker = new google.maps.Marker({
    //   map: map,
    //   position: new google.maps.LatLng(lat, lng)
    // });



    function HouseMarker(latlng, map, args) {
      this.latlng = latlng; //for google map
      this.setMap(map); //for google map
      this.args = args; //自定义参数
    }
    HouseMarker.prototype = new google.maps.OverlayView();
    HouseMarker.prototype.draw = function () {
      //创建一个div,把marker和详情框写在一起,方便后面的展示和隐藏
      $div = $("<div class='marker-container'>" +
                "  <div class='marker'></div>" +
                "  <div class='detail-info'></div>" +
                "</div>");
      //将div添加到它的dom元素里面
      var panes = this.getPanes();
      var div = $div[0];
      panes.overlayImage.appendChild(div);
      //根据经纬度计算div的像素位置
      var point = this.getProjection().fromLatLngToDivPixel(this.latlng);
      div.style.left = (point.x - 20) + 'px';    //减掉marker宽度的一半,居中
      div.style.top = (point.y - 20) + 'px';    //减掉marker高度的一半,居中
    };
    // var locationMarker = {
    //   path: './img/green.svg'
    // }
    var marker = new google.maps.Marker({
      map: map,
      // icon: './img/green.svg',
      position: new google.maps.LatLng(lat, lng)
    });
    var infowindow = new google.maps.InfoWindow({ content: "北京市天安门" }); //创建一个InfoWindow
    infowindow.open(map, marker); //把这个infoWindow绑定在选定的marker上面
    //使用谷歌地图定义的事件,给这个marker添加点击事件
    google.maps.event.addListener(marker, "click", function () {
      infowindow.open(map, marker);
    });
  </script>
</body>

</html>

2.谷歌地图自定义标记以及点击事件
实现效果
这里写图片描述
多个标记的话,只展示一个,这时候我们要用数组储存起来,然后通过点击对象区分是谁,然后用我们存储的当前点击事件的索引来判断是否是我们现在点击对象。也即是说我们要存储起来三个值,marker标记,infowindow弹出框,还有存在当前弹框的对象索引值

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
  <title>地图研究</title>
  <style>
    body,
    html {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
    }

    .gm-style div div div div div div:last-child {
      background-color: rgba(0, 0, 0, 0) !important;
    }

    .gm-style div div div div div div:nth-child(2) {
      background-color: rgba(0, 0, 0, 0) !important;
      box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px !important;
    }

    .gm-style div div div div div div:nth-child(1) div {
      /* display: none !important; */
    }

    .gm-style .gm-style-iw .marker-container {
      width: 200px;
      height: 250px;
      background-color: rgba(28, 40, 52, .6) !important;
      z-index: 1000000;
      color: #00a2ff;
      border: 1px solid rgba(255, 255, 255, .1);
      position: relative;
    }

    .marker {
      width: 90%;
      height: 45%;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      top: 5%;
      background: url('./img/house.jpg');
    }

    .detail-info {
      width: 90%;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      top: 55%;
    }

    .detail-info p {
      margin: 0;
      margin-bottom: 15px;
    }

    .detail-info span {
      display: block;
    }

    .statusAddress div {
      float: left;
      width: 50%;
    }

    .lastTime,
    .statusAddress {
      font-size: 10px;
    }

    .detail-info span:last-child {
      color: rgba(255, 255, 255, .5);
    }
  </style>
</head>

<body>
  <div id="map" style="width:70%;height:100%"></div>
  <script src="./lib/jquery.min.js"></script>
  <script src="http://ditu.google.cn/maps/api/js?key=AIzaSyD4B4IuS7uIJvBMvgptrSBK_yaoF6rTJYE&language=EN"></script>
  <!-- 中国版 -->
  <!--正常版,需FQ  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBp"></script> -->
  <script>
    var mapType = google.maps.MapTypeId.ROADMAP;
    var lat = 39.915168,
      lng = 116.403875,
      zoom = 10;
    var arr = [];
    var mapOptions = {
      center: {
        lat: 52.38027,
        lng: -1.5637500000000273
      },
      zoom: 2,
      styles: [{
          "featureType": "all",
          "elementType": "labels.text.fill",
          "stylers": [{
              "saturation": 36
            },
            {
              "color": "#1F2B37"
            },
            {
              "lightness": 1
            }
          ]
        },
        {
          "featureType": "all",
          "elementType": "labels.text.stroke",
          "stylers": [{
            "visibility": "on"
          }, {
            "color": "#1F2B37"
          }, {
            "lightness": 20
          }]
        },
        {
          "featureType": "all",
          "elementType": "labels.icon",
          "stylers": [{
            "visibility": "off"
          }]
        }, {
          "featureType": "administrative",
          "elementType": "geometry.fill",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }]
        }, {
          "featureType": "administrative",
          "elementType": "geometry.stroke",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }, {
            "weight": 1.2
          }]
        }, {
          "featureType": "landscape",
          "elementType": "geometry",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }]
        }, {
          "featureType": "poi",
          "elementType": "geometry",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }]
        }, {
          "featureType": "road.highway",
          "elementType": "geometry.fill",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }]
        }, {
          "featureType": "road.highway",
          "elementType": "geometry.stroke",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }, {
            "weight": 0.2
          }]
        }, {
          "featureType": "road.arterial",
          "elementType": "geometry",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }]
        }, {
          "featureType": "road.local",
          "elementType": "geometry",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }]
        }, {
          "featureType": "transit",
          "elementType": "geometry",
          "stylers": [{
            "color": "#1F2B37"
          }, {
            "lightness": 1
          }]
        }, {
          "featureType": "water",
          "elementType": "geometry",
          "stylers": [{
            "color": "#131d27"
          }, {
            "lightness": 0
          }]
        }
      ]
    }
    var map = new google.maps.Map(document.getElementById("map"), mapOptions); //创建谷歌地图




    var arr = [1, 2];
    var marker = [];
    var infowindow = [];
    var currentIndex = -1;

    arr.forEach(function (item, index) {
      marker[index] = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(lat + index * 10, lng - index * 50)
      });

      //创建一个InfoWindow
      // infowindow.open(map, marker); //把这个infoWindow绑定在选定的marker上面
      //使用谷歌地图定义的事件,给这个marker添加点击事件
      infowindow[index] = new google.maps.InfoWindow({
        content: "<div class='marker-container'>" +
          "  <div class='marker'></div>" +
          "  <div class='detail-info'><p class='deviceName'>heihei</p ><p class='lastTime'><span>_/_</span><span>last time</span></p ><div class='statusAddress'><div class='saLeft'><span>Alarm</span><span>status</span></div><div class='saRight'><span>120.123/30.123</span><span>address</span></div></div></div>" +
          "</div>"
      });


    })
    // 点击事件
    arr.forEach(function(item,index){

      google.maps.event.addListener(marker[index], "click", function () {
        var flag =  currentIndex === index;
        if(!flag){
          infowindow[index].open(map, marker[index]);
          if(currentIndex >= 0){
            infowindow[currentIndex].close(map, marker[currentIndex]);
          }
          currentIndex = index;
        }else{

          infowindow[currentIndex].close(map, marker[currentIndex]);
          currentIndex = -1
        }


      });
    })

    // google.maps.event.addListener(marker, 'mouseover', function() {  
    //   infowindow.open(map, marker);  
    //     });  
    //     google.maps.event.addListener(marker, 'mouseout', function() {  
    //       infowindow.close(map, marker);  
    //     });  

    function HouseMarker(latlng, map, args) {
      this.latlng = latlng; //for google map
      this.prototype.setMap(map); //for google map
      // this.map = map,
      this.args = args; //自定义参数
    }
    // console.log(google.maps)
    // HouseMarker.prototype = new google.maps.OverlayView();
    HouseMarker.prototype = google.maps.OverlayView;

    // HouseMarker.prototype.draw = function () {
    //   //创建一个div,把marker和详情框写在一起,方便后面的展示和隐藏
    //   $div = $("<div class='marker-container'>" +
    //             "  <div class='marker'></div>" +
    //             "  <div class='detail-info'></div>" +
    //             "</div>");
    //     console.log(this.prototype,'gaga');
    //     console.log(this.prototype.getPanes)
    //     console.log(this.prototype.getPanes())
    //   //将div添加到它的dom元素里面
    //   var panes = this.prototype.getPanes();
    //   console.log(panes)

    //   var div = $div[0];
    //   panes.overlayImage.appendChild(div);
    //根据经纬度计算div的像素位置
    // var point = this.prototype.getProjection().fromLatLngToDivPixel(this.latlng);
    // div.style.left = (point.x - 20) + 'px';    //减掉marker宽度的一半,居中
    // div.style.top = (point.y - 20) + 'px';    //减掉marker高度的一半,居中
    // };
    // console.log(HouseMarker.prototype)
    // var marker = new HouseMarker('39.915168,116.403875',map);
    // marker.draw();
    // console.log(marker.draw())
    // var locationMarker = {
    //   path: './img/green.svg'
    // }
  </script>
</body>

</html>

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;