勉強したことのメモ

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

  関連記事

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

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

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

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

Google Maps APIで現在地取得と目的地までのルートを表示させる方法

Google Maps APIを使って現在地を取得しつつ、目的地までのルートを表 ...

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

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

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

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