地図にはさまざまなシェイプを追加できます。シェイプは地図上のオブジェクトであり、緯度 / 経度座標と紐付けされています。使用できるシェイプとしては、ライン、ポリゴン、円、長方形があります。また、ユーザーがシェイプを編集またはドラッグできるように設定できます。
ポリライン
地図上にラインを描画するにはポリラインを使用します。
Polyline クラスは地図上で連結された一連のラインからなる線形オーバーレイを定義します。Polyline オブジェクトは LatLng 位置の配列で構成され、これらの位置を決まった順序で連結する一連の線分を作成します。
ポリラインを追加する
Polyline コンストラクタはラインの LatLng 座標を指定する一連の PolylineOptions と一連のスタイルを受け取り、ポリラインの視覚的な動作を調整します。
Polyline オブジェクトは、一連の直線セグメントとして地図上に描画されます。ラインの構成時に PolylineOptions 内で、ライン ストロークの色、太さ、不透明度をカスタムで指定できます。または、構成後にこれらのプロパティを変更できます。
ポリラインがサポートしているストローク スタイルは次のとおりです。
strokeColorには、フォーマット"#FFFFFF"の 16 進数 HTML カラーを指定します。Polylineクラスでは色名はサポートされていません。strokeOpacityには、ラインの色の不透明度を示す数値を0.0~1.0の間で指定します。デフォルト値は1.0です。strokeWeightには、ラインの幅をピクセル単位で指定します。
ポリラインの editable プロパティを使用すると、ユーザーがシェイプを編集できるかどうかを指定できます。詳しくは、下記のユーザーによる編集とドラッグが可能なシェイプをご覧ください。同様に、draggable プロパティを設定して、ユーザーにラインのドラッグを許可するかどうかを設定することもできます。
この例では、カリフォルニア州オークランドとオーストラリアのブリスベン間の最初の太平洋横断飛行の経路を示す、幅 2 ピクセルの赤いポリラインを作成します。
TypeScript
// This example creates a 2-pixel-wide red polyline showing the path of // the first trans-Pacific flight between Oakland, CA, and Brisbane, // Australia which was made by Charles Kingsford Smith. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 3, center: { lat: 0, lng: -180 }, mapTypeId: "terrain", } ); const flightPlanCoordinates = [ { lat: 37.772, lng: -122.214 }, { lat: 21.291, lng: -157.821 }, { lat: -18.142, lng: 178.431 }, { lat: -27.467, lng: 153.027 }, ]; const flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a 2-pixel-wide red polyline showing the path of // the first trans-Pacific flight between Oakland, CA, and Brisbane, // Australia which was made by Charles Kingsford Smith. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 3, center: { lat: 0, lng: -180 }, mapTypeId: "terrain", }); const flightPlanCoordinates = [ { lat: 37.772, lng: -122.214 }, { lat: 21.291, lng: -157.821 }, { lat: -18.142, lng: 178.431 }, { lat: -27.467, lng: 153.027 }, ]; const flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(map); } window.initMap = initMap;
サンプルを試す
ポリラインを除去する
地図からポリラインを除去するには、setMap() メソッドを呼び出して、引数として null を渡します。次のサンプルでは、flightPath がポリライン オブジェクトです。
flightPath.setMap(null);
上記のメソッドでは、ポリラインは削除されないことにご注意ください。地図からポリラインが除去されるだけです。ポリラインを削除する場合は、ポリラインを地図から除去して、そのポリライン自体を null に設定します。
ポリラインを検査する
ポリラインは、一連の座標を LatLng オブジェクトの配列として指定します。これらの座標はラインのパスを決定します。座標を取得するには、getPath() を呼び出します。これにより MVCArray タイプの配列が返されます。次の方法で、この配列を操作および検査できます。
getAt()は指定されたゼロベースのインデックス値にLatLngを返します。insertAt()は、渡されたLatLngを指定されたゼロベースのインデックス値に挿入します。そのインデックス値の既存の座標は、先送りになります。removeAt()は指定されたゼロベースのインデックス値のLatLngを削除します。
次の例は、クリックに基づいてポリラインを構築する方法を示しています(地図をクリックして頂点を追加します)。
TypeScript
// This example creates an interactive map which constructs a polyline based on // user clicks. Note that the polyline only appears once its path property // contains two LatLng coordinates. let poly: google.maps.Polyline; let map: google.maps.Map; function initMap(): void { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { zoom: 7, center: { lat: 41.879, lng: -87.624 }, // Center the map on Chicago, USA. }); poly = new google.maps.Polyline({ strokeColor: "#000000", strokeOpacity: 1.0, strokeWeight: 3, }); poly.setMap(map); // Add a listener for the click event map.addListener("click", addLatLng); } // Handles click events on a map, and adds a new point to the Polyline. function addLatLng(event: google.maps.MapMouseEvent) { const path = poly.getPath(); // Because path is an MVCArray, we can simply append a new coordinate // and it will automatically appear. path.push(event.latLng as google.maps.LatLng); // Add a new marker at the new plotted point on the polyline. new google.maps.Marker({ position: event.latLng, title: "#" + path.getLength(), map: map, }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates an interactive map which constructs a polyline based on // user clicks. Note that the polyline only appears once its path property // contains two LatLng coordinates. let poly; let map; function initMap() { map = new google.maps.Map(document.getElementById("map"), { zoom: 7, center: { lat: 41.879, lng: -87.624 }, // Center the map on Chicago, USA. }); poly = new google.maps.Polyline({ strokeColor: "#000000", strokeOpacity: 1.0, strokeWeight: 3, }); poly.setMap(map); // Add a listener for the click event map.addListener("click", addLatLng); } // Handles click events on a map, and adds a new point to the Polyline. function addLatLng(event) { const path = poly.getPath(); // Because path is an MVCArray, we can simply append a new coordinate // and it will automatically appear. path.push(event.latLng); // Add a new marker at the new plotted point on the polyline. new google.maps.Marker({ position: event.latLng, title: "#" + path.getLength(), map: map, }); } window.initMap = initMap;
サンプルを試す
ポリラインをカスタマイズする
ポリラインには、ベクターベースの画像を記号として追加できます。記号と PolylineOptions クラスを組み合わせることで、地図上のポリラインの外観を自由にカスタマイズできます。詳しくは、記号に関する記事の矢印、破線、カスタム記号、アニメーション記号についての各説明をご覧ください。
ポリゴン
ポリゴンは閉じられたパス(またはループ)により囲まれた領域を表し、一連の座標により定義されます。Polygon オブジェクトは、指定された順序の一連の座標で構成されている点で Polyline オブジェクトと似ています。ポリゴンは、ストロークと塗りつぶしにより描画されます。ポリゴンの縁(ストローク)の色、太さ、不透明度、および閉じられた領域(塗りつぶし)の色、不透明度をカスタムで定義できます。色は 16 進数の HTML 形式で指定します。色名はサポートされていません。
Polygon オブジェクトを使うと、次のような複雑なシェイプを描画できます。
- 単一のポリゴンで定義される、隣接しない複数の領域。
- 中に穴がある領域。
- 1 つ以上の領域の共通部分。
複雑なシェイプを定義するには、複数のパスを持つポリゴンを使用します。
注: データレイヤを使用すると、ポリゴンを簡単に描画できます。たとえば、ポリゴンの曲線処理により、穴があるポリゴンを簡単に描画できます。詳しくは、データレイヤのドキュメントをご覧ください。
ポリゴンを追加する
ポリゴンの領域には複数の個別のパスが含まれている場合があるため、Polygon オブジェクトの paths プロパティでは配列の配列を指定します。各配列のタイプは MVCArray です。各配列では、順序が指定された一連の LatLng 座標が個別に定義されます。
1 つのパスのみで構成される単純なポリゴンの場合、単一の LatLng 座標配列を使用して Polygon を構成できます。Maps JavaScript API では、構成時にこの単純な配列を paths プロパティに格納する際、配列の配列に変換されます。1 つのパスで構成されるポリゴン用に、API では単純な getPath() メソッドが用意されています。
ポリゴンの editable プロパティを使用すると、ユーザーがシェイプを編集できるかどうかを指定できます。詳しくは、下記のユーザーによる編集とドラッグが可能なシェイプをご覧ください。同様に、draggable プロパティを設定して、ユーザーにシェイプのドラッグを許可するかどうかを設定することもできます。
TypeScript
// This example creates a simple polygon representing the Bermuda Triangle. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", } ); // Define the LatLng coordinates for the polygon's path. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, { lat: 25.774, lng: -80.19 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a simple polygon representing the Bermuda Triangle. function initMap() { const 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. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, { lat: 25.774, lng: -80.19 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } window.initMap = initMap;
サンプルを試す
ポリゴンの自動完成
上のサンプルの Polygon は、4 セットの LatLng 座標で構成されていますが、最初と最後のセットは同じ位置を定義し、ループを完成しています。しかし、実際は、ポリゴンは閉じられた領域を定義するため、最後の座標セットを定義する必要はありません。Maps JavaScript API では、任意の指定されたパスについて、最後の場所から最初の場所に接続するストロークを描画して、自動的にポリゴンを完成します。
次のサンプルは前のサンプルと同じですが、最後の LatLng が省略されている点が異なります。
サンプルを表示
ポリゴンを除去する
地図からポリゴンを除去するには、setMap() メソッドを呼び出して、引数として null を渡します。次のサンプルでは、bermudaTriangle がポリゴン オブジェクトです。
bermudaTriangle.setMap(null);
上記のメソッドでは、ポリゴンは削除されないことにご注意ください。地図からポリゴンが除去されるだけです。ポリゴンを削除する場合は、ポリゴンを地図から除去して、そのポリゴン自体を null に設定します。
ポリゴンを検査する
ポリゴンは、一連の座標を配列の配列として指定します。各配列のタイプは MVCArray です。「リーフ」の配列は LatLng 座標の配列で、1 つのパスを示します。これらの座標を取得するには、Polygon オブジェクトの getPaths() メソッドを呼び出します。配列は MVCArray であるため、次の方法でこの配列を操作および検査する必要があります。
getAt()は指定されたゼロベースのインデックス値にLatLngを返します。insertAt()は、渡されたLatLngを指定されたゼロベースのインデックス値に挿入します。そのインデックス値の既存の座標は、先送りになります。removeAt()は指定されたゼロベースのインデックス値のLatLngを削除します。
TypeScript
// This example creates a simple polygon representing the Bermuda Triangle. // When the user clicks on the polygon an info window opens, showing // information about the polygon's coordinates. let map: google.maps.Map; let infoWindow: google.maps.InfoWindow; function initMap(): void { map = new google.maps.Map(document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, mapTypeId: "terrain", }); // Define the LatLng coordinates for the polygon. const triangleCoords: google.maps.LatLngLiteral[] = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 3, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); // Add a listener for the click event. bermudaTriangle.addListener("click", showArrays); infoWindow = new google.maps.InfoWindow(); } function showArrays(event: any) { // Since this polygon has only one path, we can call getPath() to return the // MVCArray of LatLngs. // @ts-ignore const polygon = this as google.maps.Polygon; const vertices = polygon.getPath(); let contentString = "<b>Bermuda Triangle polygon</b><br>" + "Clicked location: <br>" + event.latLng.lat() + "," + event.latLng.lng() + "<br>"; // Iterate over the vertices. for (let i = 0; i < vertices.getLength(); i++) { const xy = vertices.getAt(i); contentString += "<br>" + "Coordinate " + i + ":<br>" + xy.lat() + "," + xy.lng(); } // Replace the info window's content and position. infoWindow.setContent(contentString); infoWindow.setPosition(event.latLng); infoWindow.open(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a simple polygon representing the Bermuda Triangle. // When the user clicks on the polygon an info window opens, showing // information about the polygon's coordinates. let map; let infoWindow; function initMap() { 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. const triangleCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Construct the polygon. const bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 3, fillColor: "#FF0000", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); // Add a listener for the click event. bermudaTriangle.addListener("click", showArrays); infoWindow = new google.maps.InfoWindow(); } function showArrays(event) { // Since this polygon has only one path, we can call getPath() to return the // MVCArray of LatLngs. // @ts-ignore const polygon = this; const vertices = polygon.getPath(); let contentString = "<b>Bermuda Triangle polygon</b><br>" + "Clicked location: <br>" + event.latLng.lat() + "," + event.latLng.lng() + "<br>"; // Iterate over the vertices. for (let i = 0; i < vertices.getLength(); i++) { const xy = vertices.getAt(i); contentString += "<br>" + "Coordinate " + i + ":<br>" + xy.lat() + "," + xy.lng(); } // Replace the info window's content and position. infoWindow.setContent(contentString); infoWindow.setPosition(event.latLng); infoWindow.open(map); } window.initMap = initMap;
サンプルを試す
ポリゴンに穴を開ける
ポリゴン内に空白の領域を作成するには、2 つのパスを作成して、一方を他方の内側にする必要があります。穴を作成するには、内側のパスを定義する各座標の順序を、外側のパスを定義する各座標の順序と逆にする必要があります。たとえば、外側のパスの各座標が時計回りである場合、内側は反時計回りにします。
注: データレイヤにより内側と外側のパスの順序が処理されるため、穴があるポリゴンを簡単に描画できます。詳しくは、データレイヤーのドキュメントをご覧ください。
次のサンプルは、2 つのパスを持つポリゴンを描画します。内側のパスは、外側のパスと逆回りに描写されます。
TypeScript
// This example creates a triangular polygon with a hole in it. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 5, center: { lat: 24.886, lng: -70.268 }, } ); // Define the LatLng coordinates for the polygon's outer path. const outerCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Define the LatLng coordinates for the polygon's inner path. // Note that the points forming the inner path are wound in the // opposite direction to those in the outer path, to form the hole. const innerCoords = [ { lat: 28.745, lng: -70.579 }, { lat: 29.57, lng: -67.514 }, { lat: 27.339, lng: -66.668 }, ]; // Construct the polygon, including both paths. const bermudaTriangle = new google.maps.Polygon({ paths: [outerCoords, innerCoords], strokeColor: "#FFC107", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FFC107", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a triangular polygon with a hole in it. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 5, center: { lat: 24.886, lng: -70.268 }, }); // Define the LatLng coordinates for the polygon's outer path. const outerCoords = [ { lat: 25.774, lng: -80.19 }, { lat: 18.466, lng: -66.118 }, { lat: 32.321, lng: -64.757 }, ]; // Define the LatLng coordinates for the polygon's inner path. // Note that the points forming the inner path are wound in the // opposite direction to those in the outer path, to form the hole. const innerCoords = [ { lat: 28.745, lng: -70.579 }, { lat: 29.57, lng: -67.514 }, { lat: 27.339, lng: -66.668 }, ]; // Construct the polygon, including both paths. const bermudaTriangle = new google.maps.Polygon({ paths: [outerCoords, innerCoords], strokeColor: "#FFC107", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FFC107", fillOpacity: 0.35, }); bermudaTriangle.setMap(map); } window.initMap = initMap;
サンプルを試す
長方形
汎用の Polygon クラスに加え、Google Maps JavaScript API には構成を簡素化するために Rectangle オブジェクト用の特別なクラスが含まれています。
長方形を追加する
長方形の縁(ストローク)の色、太さ、不透明度、および長方形内(塗りつぶし)の色、不透明度をカスタムで定義できる点で、Rectangle は Polygon と似ています。色は 16 進数の HTML スタイルで示す必要があります。
Polygon とは異なり、Rectangle では paths は定義しません。その代わりに、bounds プロパティの google.maps.LatLngBounds を指定してその形状を定義します。
長方形の editable プロパティを使用すると、ユーザーがシェイプを編集できるかどうかを指定できます。詳しくは、下記のユーザーによる編集とドラッグが可能なシェイプをご覧ください。同様に、draggable プロパティを設定して、ユーザーに長方形のドラッグを許可するかどうかを設定することもできます。
TypeScript
// This example adds a red rectangle to a map. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 11, center: { lat: 33.678, lng: -116.243 }, mapTypeId: "terrain", } ); const rectangle = new google.maps.Rectangle({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: { north: 33.685, south: 33.671, east: -116.234, west: -116.251, }, }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example adds a red rectangle to a map. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 11, center: { lat: 33.678, lng: -116.243 }, mapTypeId: "terrain", }); const rectangle = new google.maps.Rectangle({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: { north: 33.685, south: 33.671, east: -116.234, west: -116.251, }, }); } window.initMap = initMap;
サンプルを試す
次のコードにより、ユーザーが地図のズームを変更するたびに長方形が作成されます。長方形のサイズは、ビューポートにより決定されます。
TypeScript
// This example creates a rectangle based on the viewport // on any 'zoom-changed' event. function initMap(): void { const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 11, center: { lat: 40.74852, lng: -73.981687 }, mapTypeId: "terrain", } ); const rectangle = new google.maps.Rectangle(); map.addListener("zoom_changed", () => { // Get the current bounds, which reflect the bounds before the zoom. rectangle.setOptions({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: map.getBounds() as google.maps.LatLngBounds, }); }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example creates a rectangle based on the viewport // on any 'zoom-changed' event. function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 11, center: { lat: 40.74852, lng: -73.981687 }, mapTypeId: "terrain", }); const rectangle = new google.maps.Rectangle(); map.addListener("zoom_changed", () => { // Get the current bounds, which reflect the bounds before the zoom. rectangle.setOptions({ strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35, map, bounds: map.getBounds(), }); }); } window.initMap = initMap;
サンプルを試す
長方形を除去する
地図から長方形を除去するには、setMap() メソッドを呼び出して、引数として null を渡します。
rectangle.setMap(null);
上記のメソッドでは、長方形は削除されないことにご注意ください。地図から長方形が除去されるだけです。長方形を削除する場合は、長方形を地図から除去して、その長方形自体を null に設定します。
円
汎用の Polygon クラスに加え、Google Maps JavaScript API には構成を簡素化するために Circle オブジェクト用の特別なクラスが含まれています。
円を追加する
円の縁(ストローク)の色、太さ、不透明度、および円内(塗りつぶし)の色、不透明度をカスタムで定義できる点で、Circle は Polygon と似ています。色は 16 進数の HTML スタイルで示す必要があります。
Polygon とは異なり、Circle では paths は定義しません。その代わりに、次の 2 つのプロパティを指定してその形状を定義します。
centerは、円の中心のgoogle.maps.LatLngを指定します。radiusは、円の半径をメートル単位で指定します。
円の editable プロパティを使用すると、ユーザーがシェイプを編集できるかどうかを指定できます。詳しくは、下記のユーザーによる編集とドラッグが可能なシェイプをご覧ください。同様に、draggable プロパティを設定して、ユーザーに円のドラッグを許可するかどうかを設定することもできます。
次の例では、円を使用して、日本の京都の場所間の徒歩での所要時間のおおよその目安を示しています。メニューから必要な距離を選択し、地図をクリックして円の中心を再設定し、円をドラッグして位置を変更します。
TypeScript
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; let innerMap; async function initMap() { // Import the needed libraries. // Request needed libraries. (await google.maps.importLibrary('maps')) as google.maps.MapsLibrary; (await google.maps.importLibrary('marker')) as google.maps.MarkerLibrary; // Get the gmp-map element. const mapElement = document.querySelector( 'gmp-map' ) as google.maps.MapElement; const initialCenter = { lat: 34.98956821576194, lng: 135.74239981260283 }; // Hotel Emion, Kyoto, Japan // Get the inner map. const innerMap = mapElement.innerMap; const buttons = document.querySelectorAll('input[name="radius"]'); const walkingCircle = new google.maps.Circle({ strokeColor: '#ffdd00ff', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#ffdd00ff', fillOpacity: 0.35, map: innerMap, center: initialCenter, radius: 400, draggable: true, editable: false, }); // Define a "Crosshair" vector icon const parser = new DOMParser(); const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="-6 -6 12 12"><path d="M -6,0 L 6,0 M 0,-6 L 0,6" stroke="black" stroke-width="1"/></svg>`; const pinSvg = parser.parseFromString( svgString, 'image/svg+xml' ).documentElement; const centerMarker = new google.maps.marker.AdvancedMarkerElement({ position: initialCenter, title: 'A marker using a custom SVG image.', //@ts-ignore anchorLeft: '-50%', anchorTop: '-50%', }); centerMarker.append(pinSvg); mapElement.append(centerMarker); // Wait for the map to finish drawing its tiles. google.maps.event.addListenerOnce(innerMap, 'tilesloaded', function () { // Get the controls div const controls = document.getElementById('control-panel'); // Display controls once map is loaded. if (controls) { controls.style.display = 'block'; } }); // Add event listener to update the radius based on user selection. buttons.forEach((button) => { button.addEventListener('change', (event) => { const target = event.target as HTMLInputElement; walkingCircle.setRadius(Number(target.value)); }); }); // Handle user click, reset the map center and position the circle. innerMap.addListener('click', (mapsMouseEvent) => { const newCenter = mapsMouseEvent.latLng; walkingCircle.setCenter(newCenter); centerMarker.position = newCenter; innerMap.panTo(newCenter); }); // Handle user dragging the circle, update the center marker position. walkingCircle.addListener('center_changed', () => { centerMarker.position = walkingCircle.getCenter(); }); } initMap();
JavaScript
const mapElement = document.querySelector('gmp-map'); let innerMap; async function initMap() { // Import the needed libraries. // Request needed libraries. (await google.maps.importLibrary('maps')); (await google.maps.importLibrary('marker')); // Get the gmp-map element. const mapElement = document.querySelector('gmp-map'); const initialCenter = { lat: 34.98956821576194, lng: 135.74239981260283 }; // Hotel Emion, Kyoto, Japan // Get the inner map. const innerMap = mapElement.innerMap; const buttons = document.querySelectorAll('input[name="radius"]'); const walkingCircle = new google.maps.Circle({ strokeColor: '#ffdd00ff', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#ffdd00ff', fillOpacity: 0.35, map: innerMap, center: initialCenter, radius: 400, draggable: true, editable: false, }); // Define a "Crosshair" vector icon const parser = new DOMParser(); const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="-6 -6 12 12"><path d="M -6,0 L 6,0 M 0,-6 L 0,6" stroke="black" stroke-width="1"/></svg>`; const pinSvg = parser.parseFromString(svgString, 'image/svg+xml').documentElement; const centerMarker = new google.maps.marker.AdvancedMarkerElement({ position: initialCenter, title: 'A marker using a custom SVG image.', //@ts-ignore anchorLeft: '-50%', anchorTop: '-50%', }); centerMarker.append(pinSvg); mapElement.append(centerMarker); // Wait for the map to finish drawing its tiles. google.maps.event.addListenerOnce(innerMap, 'tilesloaded', function () { // Get the controls div const controls = document.getElementById('control-panel'); // Display controls once map is loaded. if (controls) { controls.style.display = 'block'; } }); // Add event listener to update the radius based on user selection. buttons.forEach((button) => { button.addEventListener('change', (event) => { const target = event.target; walkingCircle.setRadius(Number(target.value)); }); }); // Handle user click, reset the map center and position the circle. innerMap.addListener('click', (mapsMouseEvent) => { const newCenter = mapsMouseEvent.latLng; walkingCircle.setCenter(newCenter); centerMarker.position = newCenter; innerMap.panTo(newCenter); }); // Handle user dragging the circle, update the center marker position. walkingCircle.addListener('center_changed', () => { centerMarker.position = walkingCircle.getCenter(); }); } initMap();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } #control-panel { display: none; /* Set to 'display: block' after the map loads. */ background-color: #fff; border: 2px solid #fff; border-radius: 3px; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); font-family: "Roboto", "sans-serif"; font-size: medium; margin: 10px; padding: 10px; }
HTML
<html>
<head>
<title>Circles</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- prettier-ignore -->
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
({key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script>
</head>
<body>
<gmp-map
center="34.98956821576194, 135.74239981260283"
zoom="15"
map-id="DEMO_MAP_ID">
<div id="control-panel" slot="control-inline-start-block-start">
<input
id="short-walk"
type="radio"
name="radius"
value="400"
checked />
<label for="short-walk">Short Walk (~5 minutes)</label><br />
<input
id="medium-walk"
type="radio"
name="radius"
value="800" />
<label for="medium-walk">Medium Walk (~15 minutes)</label><br />
<input id="long-walk" type="radio" name="radius" value="1600" />
<label for="long-walk">Long Walk (~30 minutes) </label>
</div>
</gmp-map>
</body>
</html>サンプルを試す
円を除去する
地図から円を除去するには、setMap() メソッドを呼び出して、引数として null を渡します。
circle.setMap(null);
上記のメソッドでは、円は削除されないことにご注意ください。地図から円が除去されるだけです。円を削除する場合は、円を地図から除去して、その円自体を null に設定します。
ユーザーによる編集とドラッグが可能なシェイプ
シェイプを編集可能にすると、ハンドルが追加されます。ユーザーは、そのハンドルを使用してシェイプの移動、形状の変更、およびサイズの変更を地図上で直接行うことができます。また、ユーザーがシェイプを地図上の別の場所に移動できるように、シェイプをドラッグ可能にすることもできます。
ユーザーが行ったオブジェクトの変更は、セッション間で保持されません。ユーザーの編集を保存する場合は、アプリケーションで情報をキャプチャして保存する必要があります。
シェイプを編集可能にする
どのシェイプ(ポリライン、ポリゴン、円、長方形)でも、シェイプのオプションで editable を true に設定することでユーザーによる編集を可能にできます。
var bounds = { north: 44.599, south: 44.490, east: -78.443, west: -78.649 }; // Define a rectangle and set its editable property to true. var rectangle = new google.maps.Rectangle({ bounds: bounds, editable: true });
シェイプをドラッグ可能にする
デフォルトでは、地図上に描画されたシェイプの位置は固定されています。ユーザーがシェイプを地図上の別の場所にドラッグできるようにするには、シェイプのオプションで draggable を true に設定します。
var redCoords = [ {lat: 25.774, lng: -80.190}, {lat: 18.466, lng: -66.118}, {lat: 32.321, lng: -64.757} ]; // Construct a draggable red triangle with geodesic set to true. new google.maps.Polygon({ map: map, paths: redCoords, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, draggable: true, geodesic: true });
ポリゴンまたはポリラインをドラッグ可能にする場合に、geodesic プロパティを true に設定して、ポリゴンまたはポリラインを測地線的にすることもできます。
測地線的なポリゴンは、移動された場合に地理的な真の形状を保持します。そのため、メルカトル図法で北または南に移動すると、歪んで表示されます。測地線的でないポリゴンの場合は、画面上のその最初の外観が常に保持されます。
測地線的なポリラインでは、地球が球体であると仮定して、ポリラインのセグメントは地球表面上の 2 点間の最短経路として描画されるため、メルカトル図法上の直線とは異なります。
座標系について詳しくは、地図とタイル座標のガイドをご覧ください。
次の地図は、ほぼ同じサイズと外形の 2 つの三角形を示しています。赤い三角形は geodesic プロパティが true に設定されています。北に移動するとどのように形状が変化するか注目してください。
編集イベントをリッスンする
シェイプが編集されると、編集の完了時にイベントが発行されます。これらのイベントを以下に示します。
| シェイプ | イベント |
|---|---|
| 円 |
radius_changedcenter_changed
|
| ポリゴン |
insert_atremove_atset_at
ポリゴンのパスにリスナーを設定する必要があります。ポリゴンに複数のパスがある場合、それぞれのパス上にリスナーを設定してください。 |
| ポリライン |
insert_atremove_atset_at
ポリラインのパスにリスナーを設定する必要があります。 |
| 長方形 | bounds_changed |
有用なコード スニペット:
google.maps.event.addListener(circle, 'radius_changed', function() { console.log(circle.getRadius()); }); google.maps.event.addListener(outerPath, 'set_at', function() { console.log('Vertex moved on outer path.'); }); google.maps.event.addListener(innerPath, 'insert_at', function() { console.log('Vertex removed from inner path.'); }); google.maps.event.addListener(rectangle, 'bounds_changed', function() { console.log('Bounds changed.'); });
長方形上の編集イベントの処理については、こちらのサンプルを表示してください。
ドラッグ イベントをリッスンする
シェイプがドラッグされると、ドラッグ アクションの開始時と終了時、およびドラッグの実行中にイベントが発行されます。ポリライン、ポリゴン、円、および長方形に対して発行されるイベントを以下に示します。
| イベント | 説明 |
|---|---|
dragstart |
ユーザーがシェイプのドラッグを開始したときに発生します。 |
drag |
ユーザーがシェイプをドラッグしている間に繰り返し発生します。 |
dragend |
ユーザーがシェイプのドラッグを終了すると発行されます。 |
イベント処理について詳しくは、イベントをご覧ください。