LoginSignup
0
0

More than 5 years have passed since last update.

Google Maps APIでpolygon編集時にイベントを発生させる。

Last updated at Posted at 2018-04-18

課題

Google Map上に表示したpolygonを編集した際に、緯度経度を取得したい。
set_atイベントをaddListenerすると、ドラッグ中もイベントが発火して動きが重くなってしまう。

対応方法

以下の方法で、ドラッグ中はset_atイベントを発火しないようにした。

  1. Google Map初期化時にset_atイベントをaddListener
  2. dragstartイベントでset_atイベントをクリア。
  3. dragendイベントで緯度経度を取得しつつ、再びset_atイベントをaddListener
// Google Map初期化
initMap = () => { 
  const defaultCenter = {
    lat: xxx,
    lng: xxx,
  }
  const map = new google.maps.Map(document.getElementById('map'), {
    center: new window.google.maps.LatLng(defaultCenter.lat, defaultCenter.lng),
    zoom: 13
  });

  const polygonArea = new google.maps.Polygon({
    ...
    draggable: true,
    editable: true,
  })
  polygonArea.setMap(map)

  // set_atイベントをaddListener。
  this.addListenerSetAtToPolygonPath(polygonArea)

  google.maps.event.addListener(polygonArea.getPath(), 'insert_at', () => {
    this.setCoode(polygonArea)
  });

  google.maps.event.addListener(polygonArea, 'dragstart', () => {
    // set_atイベントをクリア。
    google.maps.event.clearListeners(polygonArea.getPath(), 'set_at')
  });

  google.maps.event.addListener(polygonArea, 'dragend', () => {
    this.setCoode(polygonArea)
    // set_atイベントをaddListener。
    this.addListenerSetAtToPolygonPath(polygonArea)
  });

  this.setCoode(polygonArea)
  console.log('map is open')
  console.log(map)
}

// polygonPathの編集時にイベント追加
addListenerSetAtToPolygonPath = (polygonArea) => {
  google.maps.event.addListener(polygonArea.getPath(), 'set_at', () => {
    this.setCoode(polygonArea)
  });
}

setCoode = (polygon) => {
  //polygonの緯度経度取得。
}

もっと良いやり方があれば教えてください。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0