勉強したことのメモ

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

  関連記事

Advanced Custom FieldsでGoogleMapの使用する方法
Advanced Custom FieldsでGoogleMapの使用する方法

Advanced Custom FieldsでGoogleMapを使用したかった ...

Google Maps APIで都道府県の中心地と県庁所在地にマーカーを立てる方法
Google Maps APIで都道府県の中心地と県庁所在地にマーカーを立てる方法

Google Maps APIで都道府県の中心地もしくは県庁所在地にマーカーを立 ...

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

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

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

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

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

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