Google Maps APIを使用していて、領域内にマーカーが設定された時などに特定の地域にそのマーカーが属しているかなど、
領域内の判定をしたいことがあると思います。
今回は、Google Maps APIを使用して領域内の判定を行うプログラムを作成してみました。
下に地図がありますが、バミューダトライアングルの地域内をクリックすると、バミューダトライアングルの領域内にいるという文言がテキストで表示され、範囲外の場合は範囲外だよとテキストで表示するプログラムです。
まず、特定の範囲をGoogle Maps APIで指定するためには、Google Maps APIのPolygonを使用します。
指定範囲がクリックされているかの判定には、containsLocation()を使用して判定しています。
実際にプログラムは下記となります。
<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Simple Polygon</title> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #res { height: 10%; } #map { height: 90%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="res"></div> <div id="map"></div> <script> var marker; var bermudaTriangle // This example creates a simple polygon representing the Bermuda Triangle. function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: {lat: 24.886, lng: -70.268}, mapTypeId: 'terrain' }); // Define the LatLng coordinates for the polygon's path. var triangleCoords = [ {lat: 25.774, lng: -80.190}, {lat: 18.466, lng: -66.118}, {lat: 32.321, lng: -64.757}, {lat: 25.774, lng: -80.190} ]; // 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); google.maps.event.addListener(map, 'click', clickEventFunc); google.maps.event.addListener(bermudaTriangle, 'click', clickEventFunc); } function clickEventFunc(event) { //marker.setMap(null); var latlng = new google.maps.LatLng(event.latLng.lat(),event.latLng.lng()); var res = google.maps.geometry.poly.containsLocation(latlng, bermudaTriangle); var msg = ""; if(res){ msg = "クリックされた地点は、バミューダトライアングル範囲内に入っています。" }else{ msg = "クリックされた地点は、バミューダトライアングル範囲外です。" } document.getElementById("res").innerText = msg; } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=your_api_key&callback=initMap"> </script> </body> </html>
アプリなどでGPSの情報を取って、その情報をWEBで指定範囲内にいるかなどの判定をする必要に迫られた際など、使う機会もあるかもしれません。
Google Maps APIで領域内の判定を行いたいと思った際には参考にしてください。