勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

GoogleMapAPIでクリックした座標にマーカーを設置する方法

   2024/02/20  Google Maps API Google

GoogleMapAPIでクリックした位置にマーカーを設置し、座標の経度緯度をテキストボックスに自動で入力させたかった。また、既に設置されているマーカーは削除、新しく設置したマーカーがマップの中心に来るよう移動させたい。以下に方法をメモ。

 

リファレンス

https://developers.google.com/maps/documentation/javascript/reference/map?hl=ja#Map.panTo

 

HTML部分

<!-- 住所 -->
<input type="text" name="address" id="address">
<!-- 住所 -->
 
<!-- 緯度 -->
<input type="text" name="lat" id="lat">
<!-- 緯度 -->
 
<!-- 経度 -->
<input type="text" name="long" id="long" class="form-control form-control-sm">
<!-- 経度 -->
 
<!-- GoogleMap -->
<div id="map_canvas" style="width: 100%; height: 300px;"></div>
<!-- GoogleMap -->

 

javascript部分

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=true&key=xxxxxxxxxxxxxxxxx"></script>
<script>
var map;
var marker;

//GoogleMap初期表示
var init_latlng = {'lat' : '35.681236', 'long' : '139.767125'};
var latlng = new google.maps.LatLng(init_latlng.lat, init_latlng.long);
var myOptions = {
    zoom: 12, 
    gestureHandling: "greedy" ,
    center: latlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP, 
    "streetViewControl": false, 
    "fullscreenControl": false, 
    "styles": false, 
    "disableDoubleClickZoom": false, 
    "mapTypeControl": false, 
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var mapData = { 'x':init_latlng.lat, 'y':init_latlng.long };

//マーカー設置
makeMarker(mapData);

//マーカー作成用関数
function makeMarker( mapData ){
    marker = new google.maps.Marker({
        position : new google.maps.LatLng(mapData.x,mapData.y), 
        map: map, 
    });
}

//クリックで経度緯度取得
map.addListener('click', clickLatLng);
function clickLatLng(event){

    //クリックした位置の座標を取得
    var click_latlng = event.latLng;

    //経度緯度をテキストボックスに入力
    $('#lat').val(click_latlng.lat());
    $('#long').val(click_latlng.lng());

    //既存マーカーを消去
    marker.setMap(null);

    //マーカー設置
    mapData = { 'x':click_latlng.lat(), 'y':click_latlng.lng() };
    makeMarker(mapData);

    //マーカー位置に移動
    map.panTo(new google.maps.LatLng(click_latlng.lat(),click_latlng.lng()));
}
</script>

 - Google Maps API Google

  関連記事

GoogleMapAPIでジオコーディングできない場合の対応方法

住所から経度緯度を取得するジオコーディングをGoogleMapAPIを用いて行お ...

Google Maps APIでヒートマップを表示する方法

Google Maps APIで花粉状況や雨量を可視化しやすいようなヒートマップ ...

androidでgeolocationを使うとtimeoutになる

Geolocation APIを用いて現在地をGoogleMapに表示させるとい ...

Google Maps APIで都道府県の中心地と県庁所在地にマーカーを立てる方法

Google Maps APIで都道府県の中心地もしくは県庁所在地にマーカーを立 ...

Google Maps APIでリアルタイムに現在地のマーカーを更新する方法

GoogleMapAPIを使って現在地を取得してその場所にマーカーを設置、その後 ...