最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I add and remove Polygons on Google Maps v3? - Stack Overflow

programmeradmin0浏览0评论

I'm trying to show and remove polygons onto a Google Map, using v3 of the API. In my JavaScript, I've already got an MVCArray of some custom Lat-Longs.

I'm trying to figure out how to add these polygons and then, based upon some other JavaScript event or user action, such as a click on a polygon (that has been rendered), that polygon will be removed.

Are any code examples available? I'm struggling to find some; most of them usually go to some v2 code.

I'm trying to show and remove polygons onto a Google Map, using v3 of the API. In my JavaScript, I've already got an MVCArray of some custom Lat-Longs.

I'm trying to figure out how to add these polygons and then, based upon some other JavaScript event or user action, such as a click on a polygon (that has been rendered), that polygon will be removed.

Are any code examples available? I'm struggling to find some; most of them usually go to some v2 code.

Share Improve this question edited Dec 10, 2021 at 20:40 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Aug 6, 2010 at 12:12 Pure.KromePure.Krome 87k120 gold badges424 silver badges685 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 27

In the API docs, there are a couple of simple examples of adding a polygon to a map. Here's the initialize() function from the simple Bermuda Triangle example with the addition of adding an event listener to remove the polygon when clicked.

function initialize() {
  var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
  var myOptions = {
    zoom: 5,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var bermudaTriangle;

  var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);

  var triangleCoords = [
      new google.maps.LatLng(25.774252, -80.190262),
      new google.maps.LatLng(18.466465, -66.118292),
      new google.maps.LatLng(32.321384, -64.75737),
      new google.maps.LatLng(25.774252, -80.190262)
  ];

  // Construct the polygon
  bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35
  });

  bermudaTriangle.setMap(map);

  // add an event listener
  google.maps.event.addListener(bermudaTriangle, 'click', function() {
      this.setMap(null);
  });

}

I'm not sure if this answer applies to javascript, but definitely applies to java.

If you have a reference to the polygon object you want to remove, then simply call the remove() method of that polygon. Refer to the documentation linked below.

https://developers.google.com/android/reference/com/google/android/gms/maps/model/Polygon.html#remove()

发布评论

评论列表(0)

  1. 暂无评论