はじめに
マーカーは、地図上の場所を識別します。デフォルトでは、マーカーは標準画像です。マーカーは、カスタム画像を表示できます。この場合、通常はアイコンと呼ばれます。マーカーとアイコンは、Marker タイプのオブジェクトです。カスタム アイコンはマーカーのコンストラクタ内に設定できます。または、マーカー上で setIcon() を呼び出して設定できます。マーカー画像のカスタマイズの詳細については、下記をご覧ください。
大まかに言うと、マーカーは一種のオーバーレイです。その他のオーバーレイのタイプについては、マップ上に描画するをご覧ください。
マーカーは、インタラクティブに動作するように設計されています。たとえば、デフォルトでマーカーは 'click' イベントを受信します。したがって、イベントリスナを追加して、カスタム情報を表示する情報ウィンドウを表示できます。マーカーの draggable プロパティを true に設定して、ユーザーにマップ上のマーカーの移動を許可することができます。ドラッグ可能マーカーの詳細については、下記をご覧ください。
マーカーを追加する
google.maps.Marker コンストラクタでは、単一の Marker options オブジェクト リテラルを受け取ってマーカーの初期プロパティを指定します。
以下のフィールドは、特に重要であり、マーカーの構築時に一般的に設定されます。
position(必須)はLatLngを指定し、マーカーの初期位置を特定します。LatLngを取得する方法の 1 つとして、ジオコーディング サービスを使用できます。map(任意)はマーカーを配置するMapを指定します。マーカーの構築時にマップを指定しない場合、マーカーは作成されますがマップに関連付けられません(表示されません)。マーカーのsetMap()メソッドを呼び出して、マーカーを後で追加できます。
次の例は、単純なマーカーを、オーストラリアの中央部にあるウルルに追加しています。
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
上記の例では、マーカーはマーカー オプションの map プロパティを使用して、マーカーの構築時にマップ上に配置されます。または、次の例に示すように、マーカーの setMap() メソッドを使用して、マーカーをマップに直接追加できます。
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
マーカーの title が、ツールヒントとして表示されます。
マーカーのコンストラクタ内の Marker options を何も渡さない場合は、コンストラクタの最後の引数に空のオブジェクト {} を渡します。
マーカーを除去する
マップからマーカーを除去するには、setMap() メソッドを呼び出して引数として null を渡します。
marker.setMap(null);
上記のメソッドでは、マーカーは削除されないことに注意してください。マップからマーカーが除去されるだけです。マーカーを削除する場合は、マーカーをマップから除去して、そのマーカー自体を null に設定します。
複数のマーカーを同時に管理する場合、配列を作成して複数のマーカーを保持します。マーカーの除去が必要な場合は、この配列を使用して、配列内の各マーカー上で順に setMap() を呼び出すことができます。複数のマーカーを削除するには、マップから除去して、次に配列の length を 0 に設定します。これで、マーカーへのすべての参照が除去されます。
マーカーにアニメーションを付ける
マーカーにアニメーションを付けて、さまざまな状況で動的な動きを表示できます。マーカーにどのようなアニメーションを付けるかを指定するには、google.maps.Animation タイプのマーカーの animation プロパティを使用します。次の Animation 値がサポートされています。
DROPは、マーカーを最初にマップ上に配置するときに、マーカーがマップの上部から最終的な場所まで落ちてきます。マーカーが止まるとアニメーションが終了し、animationがnullに戻ります。このタイプのアニメーションは、通常Markerの作成時に指定します。BOUNCEは、マーカーが所定の位置で跳ねることを示します。跳ねるマーカーは、animationプロパティが明示的にnullに設定されるまで跳ね続けます。
Marker オブジェクト上で setAnimation() を呼び出すことで、既存のマーカーでアニメーションを開始できます。
// The following example creates a marker in Stockholm, Sweden using a DROP
// animation. Clicking on the marker will toggle the animation between a BOUNCE
// animation and no animation.
var marker;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 59.325, lng: 18.070}
});
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: {lat: 59.327, lng: 18.067}
});
marker.addListener('click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
// The following example creates a marker in Stockholm, Sweden using a DROP
// animation. Clicking on the marker will toggle the animation between a BOUNCE
// animation and no animation.
var marker;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 59.325, lng: 18.070}
});
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: {lat: 59.327, lng: 18.067}
});
marker.addListener('click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
多数のマーカーがある場合、これらを同時にマップ上にドロップすることが望ましくないことがあります。setTimeout() を利用して、次に示すようなパターンを使用してマーカーのアニメーションに間を空けることができます。
function drop() {
for (var i =0; i < markerArray.length; i++) {
setTimeout(function() {
addMarkerMethod();
}, i * 200);
}
}
例を見る(marker-animations-iteration.html)。
マーカー画像をカスタマイズする
マーカー上に 1 つの文字または数値を配置する場合、マーカー ラベルを使えます。大規模なカスタマイズが必要な場合、アイコンを定義してデフォルトのマーカー画像の代わりに表示させることができます。アイコンを定義するには、マーカーの視覚動作を決定する多数のプロパティを設定する必要があります。
以下のセクションでは、マーカーラベル、単純なアイコン、複雑なアイコン、およびシンボル(ベクター アイコン)について説明します。
マーカーラベル
マーカーラベルは、マーカー内に表示される文字または数値です。このセクションのマーカー画像には、文字「B」を示すマーカーラベルが表示されています。マーカーラベルは、文字列、または文字列やその他のラベルプロパティを含む MarkerLabel オブジェクトとして指定できます。
マーカーを作成する際には、MarkerOptions オブジェクト内に label プロパティを指定できます。または、Marker オブジェクト上で setLabel() を呼び出して、既存マーカー上にラベルを設定できます。
次の例では、ユーザーがマップ上でクリックすると、ラベル付きマーカーが表示されます。
// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
function initialize() {
var bangalore = { lat: 12.97, lng: 77.59 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: bangalore
});
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng, map);
});
// Add a marker at the center of the map.
addMarker(bangalore, map);
}
// Adds a marker to the map.
function addMarker(location, map) {
// Add the marker at the clicked location, and add the next-available label
// from the array of alphabetical characters.
var marker = new google.maps.Marker({
position: location,
label: labels[labelIndex++ % labels.length],
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
function initialize() {
var bangalore = { lat: 12.97, lng: 77.59 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: bangalore
});
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng, map);
});
// Add a marker at the center of the map.
addMarker(bangalore, map);
}
// Adds a marker to the map.
function addMarker(location, map) {
// Add the marker at the clicked location, and add the next-available label
// from the array of alphabetical characters.
var marker = new google.maps.Marker({
position: location,
label: labels[labelIndex++ % labels.length],
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
単純なアイコン
最も基本的な場合、アイコンは単にデフォルトの Google マップ押しピンアイコンの代わりに使用する画像を示します。このようなアイコンを指定するには、マーカーの icon プロパティを画像の URL に設定します。Google Maps JavaScript API はアイコンのサイズを自動的に設定します。
// This example adds a marker to indicate the position of Bondi Beach in Sydney,
// Australia.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -33, lng: 151}
});
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var beachMarker = new google.maps.Marker({
position: {lat: -33.890, lng: 151.274},
map: map,
icon: image
});
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
// This example adds a marker to indicate the position of Bondi Beach in Sydney,
// Australia.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -33, lng: 151}
});
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var beachMarker = new google.maps.Marker({
position: {lat: -33.890, lng: 151.274},
map: map,
icon: image
});
}
複雑なアイコン
複雑な形状を指定してクリック可能な領域を示し、他のオーバーレイと相対的にアイコンをどのように表示するか(重ね順序)を指定することが必要な場合があります。この方法で指定するアイコンでは、icon プロパティに Icon タイプのオブジェクトを設定する必要があります。
Icon オブジェクトは画像を定義します。これらのオブジェクトは、アイコンの size、アイコンの origin (必要な画像がスプライト大画像の一部である場合など)、およびアイコンのホットスポットが位置する anchor (原点を基準)も定義します。
カスタム マーカーでラベルを使用している場合、Icon オブジェクトの labelOrigin プロパティでラベルの位置を指定できます。
// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: -33.9, lng: 151.2}
});
setMarkers(map);
}
// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
var beaches = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
function setMarkers(map) {
// Adds markers to the map.
// Marker sizes are expressed as a Size of X,Y where the origin of the image
// (0,0) is located in the top left of the image.
// Origins, anchor positions and coordinates of the marker increase in the X
// direction to the right and in the Y direction down.
var image = {
url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(20, 32),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 32)
};
// Shapes define the clickable region of the icon. The type defines an HTML
// <area> element 'poly' which traces out a polygon as a series of X,Y points.
// The final coordinate closes the poly by connecting to the first coordinate.
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
for (var i = 0; i < beaches.length; i++) {
var beach = beaches[i];
var marker = new google.maps.Marker({
position: {lat: beach[1], lng: beach[2]},
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
}
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: -33.9, lng: 151.2}
});
setMarkers(map);
}
// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
var beaches = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
function setMarkers(map) {
// Adds markers to the map.
// Marker sizes are expressed as a Size of X,Y where the origin of the image
// (0,0) is located in the top left of the image.
// Origins, anchor positions and coordinates of the marker increase in the X
// direction to the right and in the Y direction down.
var image = {
url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(20, 32),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 32)
};
// Shapes define the clickable region of the icon. The type defines an HTML
// <area> element 'poly' which traces out a polygon as a series of X,Y points.
// The final coordinate closes the poly by connecting to the first coordinate.
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
for (var i = 0; i < beaches.length; i++) {
var beach = beaches[i];
var marker = new google.maps.Marker({
position: {lat: beach[1], lng: beach[2]},
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
}
}
MarkerImage オブジェクトを Icon タイプに変換する
バージョン 3.10 以前の Google Maps JavaScript API では、複雑なアイコンは MarkerImage オブジェクトとして定義されていました。Icon オブジェクト リテラルは、バージョン 3.10 で追加され、3.11 以降では MarkerImage を置き換えています。Icon オブジェクト リテラルは、MarkerImage と同じパラメータをサポートし、コンストラクタを削除して、以前のパラメータを {} で囲み、各パラメータの名前を追加することで、MarkerImage を簡単に Icon に変換できます。次に例を示します。
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(25, 25));
これは次のようになります。
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
シンボル
ラスター画像に加え、マーカーでは Symbols と呼ばれるベクターパスの表示もサポートされます。ベクターパスを表示するには、必要なパスを持つ Symbol オブジェクト リテラルを、マーカーの icon プロパティに渡します。google.maps.SymbolPath 内のいずれかの事前定義済みパスを使用することも、SVG パス表記を使用してカスタムパスを定義することも可能です。
詳細については、シンボルのドキュメントをご覧ください。
マーカーをドラッグ可能にする
ユーザーがマーカーをマップ上の別の場所にドラッグできるようにするには、マーカー オプションで draggable を true に設定します。
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Place a draggable marker on the map
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable:true,
title:"Drag me!"
});
