勉強したことのメモ

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

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

   2024/01/13  Google Maps API Google

Google Maps APIでマーカーを立てて、そこから範囲●mもしくは●kmを円で表示させたかった。API自体にその機能があったので使用方法をメモ。

 

サンプル

https://taitan916.info/sample/gmap_circle/

 

事前準備

マーカーの表示と自動ズームが入ったマップの作成に関しては以前の記事のものを使用した。

https://taitan916.info/blog/?p=2403

 

JavaScript部分

var mapData = [
    { 'name':'大阪城', 'x':'34.687315', 'y':'135.526201'}, 
    { 'name':'京都タワー', 'x':'34.987574', 'y':'135.759362'}, 
];
var minLat = 999;
var maxLat = 0;
var minLng = 999;
var maxLng = 0;

var currentWindow = null;

var latlng = new google.maps.LatLng(mapData[0].x, mapData[0].y);
var myOptions = {
    center: latlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);


for (var key in mapData){
    makeMarker(mapData[key]);
}

autoZoom( maxLat, minLat, maxLng, minLng );

function makeMarker( mapData ){
    if( !mapData ) return false;

    if(mapData.x < minLat) minLat = mapData.x;
    if(mapData.x > maxLat) maxLat = mapData.x;
    if(mapData.y < minLng) minLng = mapData.y;
    if(mapData.y > maxLng) maxLng = mapData.y;

    var marker = new google.maps.Marker({
        position : new google.maps.LatLng(mapData.x,mapData.y), 
        map: map 
    });

    var infoWindow = new google.maps.InfoWindow();
    google.maps.event.addListener(marker, 'click', function() {
        if( currentWindow ) currentWindow.close();

        infoWindow.setContent(mapData.name);
        infoWindow.open(map,marker);
        currentWindow = infoWindow;
    });

    var cityCircle = new google.maps.Circle({
        strokeColor: '#FF0000', //外周の色
        strokeOpacity: 0.8, //外周の透過度
        strokeWeight: 2, //外周の太さ
        fillColor: '#FF0000', //内周の色
        fillOpacity: 0.35, //内周の透明度
        map: map, //表示させるマップ
        center: marker.position, //円の中心地
        radius: 10000 //半径(メートル)
    });

}

function autoZoom( maxLat, minLat, maxLng, minLng ){
    if( !maxLat || !minLat || !maxLng || !minLng ) return false;

    var sw = new google.maps.LatLng(maxLat,minLng);
    var ne = new google.maps.LatLng(minLat,maxLng);
    var bounds = new google.maps.LatLngBounds(sw, ne);
    map.fitBounds(bounds);
}

コメントを入れている部分が以前の記事のソースと異なる部分になる。

 

リファレンス

https://developers.google.com/maps/documentation/javascript/examples/circle-simple?hl=ja

 - Google Maps API Google

  関連記事

HTML5のGeolocation APIで位置情報を取得してGoogleMapAPIで使用する方法

GPSみたいな位置情報を取得しGoogleMapAPIでその場所を反映させたかっ ...

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

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

GoogleMapAPIで住所・経度緯度入力後にマーカーを移動させる

フォーム内に住所・経度・緯度のテキストボックスを設置し、住所を入力後にボタンを押 ...

androidでgeolocationを使うとtimeoutになる

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

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

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