勉強したことのメモ

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

  関連記事

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

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

Google Maps APIでメインカラーを変更する方法

GoogleMapAPIを用いたMAPでカラー変更をしたかった。カラーコードの指 ...

Google Maps APIで住所から経度緯度を取得する方法

やりたかった事はformに住所を入れてsubmitする際に、javascript ...

Google Maps APIで複数のマーカーをまとめる方法

Google Maps APIでマーカーを複数表示し、近隣のエリアごとにまとめて ...

androidでgeolocationを使うとtimeoutになる

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