使用谷歌地图api js绘图绘制简单的线条

时间:2017-05-22 15:56:44

标签: javascript google-maps google-maps-api-3

有没有办法允许用户使用谷歌地图js api绘制简单的线条(而不是折线)。我试图使用折线进行此操作,但没有找到任何正常的方法来制作这个人员,因为折线绘图只会在关闭结束后才会停止。在绘图时,我的意思是画圆或折线......

1 个答案:

答案 0 :(得分:0)

<style>#map_canvas {height: 400px;}</style>
<div id="map_canvas"></div>
<p>Click on the map to draw lines</p>

<script>
var polyLines = [];
var markers = [];  // marker objects
var map;

function initMap() {
  geocoder = new google.maps.Geocoder();
  var myCenter = new google.maps.LatLng(50.5, 4.5);
  var myOptions = {
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: myCenter
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  // detect click on the map.  

  var startPoint = null;
  var endPoint = null;
  map.addListener('click', function(e) {
    var lat = e.latLng.lat();
    var lng = e.latLng.lng();
    var position = {lat: lat, lng: lng};
    if(! startPoint) {
      startPoint = position;
    }
    else if(! endPoint) {
      endPoint = position;
      // so now we draw a line
      var polyLine = makePolyline([startPoint, endPoint]);
      polyLines.push(polyLine);
      // reset the points
      startPoint = null;
      endPoint = null;
    }
  });
}

// return a polyline.   If you give 2 points, it will simply be a line
function makePolyline(points) {
  return new google.maps.Polyline({
    path: points,
    // geodesic: true,     // this makes the line curvy
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2,
    map: map
  });
}

</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=geometry"></script>