勉強したことのメモ

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

Google Maps APIとPHPを組み合わせて複数マーカーとウィンドウを連携させる方法

   2024/04/18  PHP Google Maps API Google

やりたかった事は以下の通り。

  • mysqlから経度緯度、マーカー名、マーカーIDを持ってきてgooglemapにマーカーを刺す
  • マーカーをクリックするとウィンドウが表示
  • ウィンドウの中にマーカー名とリンクを表示。リンクは[?key=マーカーID]みたいにクエリをそれぞれつけたい

 

ソースコード

var currentWindow = null;

var latlng = new google.maps.LatLng(<?=$addressList[0]['x']?>,<?=$addressList[0]['y']?>); //初期位置

var myOptions = {
    zoom: 12, 
    center: latlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

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

<?php for($i = 0; $i < count($addressList); $i++){ ?>
    var addressArray = {
        'id':'<?=$addressList[$i]["id"]?>', 
        'name':'<?=$addressList[$i]["name"]?>', 
        'x':'<?=$addressList[$i]["x"]?>', 
        'y':'<?=$addressList[$i]["y"]?>'
    };
    makeMarker(addressArray);
<?php } ?>

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

    var infoWindow = new google.maps.InfoWindow();
    google.maps.event.addListener(marker, 'click', function() {
        if (currentWindow) {
            currentWindow.close();
        }
        infoWindow.setContent('マーカー名:'+addressArray.name+'<br><a href="detail.php?e='+addressArray.id+'&f=<?=$folder_id?>">詳細はコチラ</a>');
        infoWindow.open(map,marker);
        currentWindow = infoWindow;
    });
}

$addressListに予めMySQLから、マーカー情報を呼び出して配列で突っ込んでおく。

 - PHP Google Maps API Google

  関連記事

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

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

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

GoogleMapでマップ自体をドラッグして移動した後、中心地の経度緯度を取得し ...

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

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

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

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

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

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