首 页  -  技术分享  - google maps js v3 api教程(2) -- 在地图上添加标记

google maps js v3 api教程(2) -- 在地图上添加标记

分享者:陈辉     2016-02-25

google maps javascript官方文档:https://developers.google.com/maps/documentation/javascript/

我们在创建地图之后,怎么往地图上添加标记呢?

google为我们提供了google.maps.Marker这个构造函数,来创建标记。

这个函数有一个object类型的可选参数,常用的成员有:

    position: new google.maps.LatLng(lat,lng), //标记的经纬度

    map:map,  //地图对象

    icon:{

                url:'',

                size:20,

                anchor: (10,10),

                origin: (0,0)

 

           }, //标记的icon 

    draggable: true, //标记是否可以拖动

    clockable: true, //标记是否接收鼠标点击事件

    opacity: 0~1, //标记的透明度

下面我们来为地图添加一个标记,代码如下:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

      function initMap() {
        var myLatLng = {lat: -25.363, lng: 131.044};

        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: myLatLng
        });
        //创建一个marker
        var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          title: 'Hello World!'
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap">
    </script>
  </body>
</html>

如果我们想移除一个marker,则只需执行marker.setMap(null);即可。