勉強したことのメモ

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

GoogleMapAPIでマップ自体を移動し中心地の経度緯度を取得

   2024/02/20  Google Maps API Google

GoogleMapでマップ自体をドラッグして移動した後、中心地の経度緯度を取得しテキストボックスに自動で入力させたかった。以下に方法をメモ。

 

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=xxxxxxxxxx"></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('drag', dragLatLng);
function dragLatLng(){

    //マップの中心座標を取得
    var center_latlng = map.getCenter();

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

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

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

 

ドラッグイベントと中心地の取得

map.addListener('drag', dragLatLng);

上記でドラッグイベントを取得しdragLatLng関数を呼び出している。リファレンスはこちら

var center_latlng = map.getCenter();

getCenter()で経度緯度を取得しcenter_latlng変数に格納している。リファレンスはこちら

 - Google Maps API Google

  関連記事

GoogleMapAPIのジオコードで存在するはずの住所が見つからない場合の原因について(ZERO_RESULTS)

GoogleMapAPIを利用したプログラムで確かに存在するはずの住所をジオコー ...

androidでgeolocationを使うとtimeoutになる

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

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

GoogleMapAPIでクリックした位置にマーカーを設置し、座標の経度緯度をテ ...

スマホでページ内リンクからGoogleMapアプリを開く

スマホでWebページにあるリンクをクリックした際にGoogleMapアプリを表示 ...

Google Maps APIで半径●メートル範囲を円で表示する方法

Google Maps APIでマーカーを立てて、そこから範囲●mもしくは●km ...