Atelierで“番号付きマーカー”タグの付いているブログ記事

2012年9月22日

隠居のパソコン備忘録: Google Maps API JS V3 で、番号付きマーカーを表示する

 
 従来、右フレームの【晩秋の宍道湖私的観光地図】は、Google Maps API のV2版で作成したものを置いていた。V2 でかいた地図はまだ動くが、2010年5月に廃止されており、V3 へ移行することが奬められている。
 この地図では、必要性はあまりないが、マーカーに番号を表示させていた。新しく V3 で作りなおすときにも、学習も兼ねて番号を表示させたかった。

 ところが、番号入りマーカーを表示するサンプルコードが見つからない。V2 で作成したコードを V3 に置き換えることも試みたが、悲しいかな十分な知識がないし、一から勉強する意欲もないので、うまく行きそうにない。
 今までに成功した V3 のコードを眺めていると【Google Maps API JS V3 で、カテゴリー別に色違いマーカーを表示する】 で使ったコードを、わかる範囲でいじってみれば、なんとかなるのではないかと思われた。色違いのマーカーを、番号付きマーカーに置き換えるのである。この地図では、category 別に赤・青・黄色・緑などのマーカーにしているが、これを番号つきのマーカーに置き換えるのである。また、また、一つずつのマークを、一つのカテゴリーと考えるのである。
 このコードでは、マーカーを立てる地点の経度・緯度や吹きだしに表示するHTMLなどは、XML ファイルを読み込んでくることになっている。V2 で作成した地図では、HTMLの中に直接入力されていた。

 とりあえずうまく表示できるようなので、自分用の備忘録として、XML ファイルおよびHTML コードを記録しておきたい。よくわかった人から見れば、へんてこなコードとなっていると思うが、古希を超えるとほとんど羞恥心はなくなっている。

使用したXML ファイル。項目 category は num01, num02・・・のようになっている。
<?xml version="1.0" encoding="utf-8" ?> 
- <markers>
  <marker name="1:宍道湖温泉" address="   <a href="http://n-shuhei.net/atelier/photo_drive/DSC_4820-1.JPG" title="宍道湖の夕焼け" rel="lightbox[sinjiko]">宍道湖の夕焼け</a><br/>   <a href="http://n-shuhei.net/atelier/photo_drive/DSC_4831.JPG" title="宍道湖の朝" rel="lightbox[sinjiko]">宍道湖の朝</a>" lng="133.053875" lat="35.469199" category="num01" /> 
  <marker name="2:米子水鳥公園" address="   <a href="http://n-shuhei.net/atelier/photo_digisco/DSC01539.JPG" title="コハクチョウ" rel="lightbox[sinjiko]" >コハクチョウ</a><br/>   <a href="http://n-shuhei.net/atelier/photo_digisco/DSC01510.JPG" title="オナガガモ:♀を追いかける♂たち" rel="lightbox[sinjiko]" >オナガガモ</a><br/>   <a href="http://n-shuhei.net/atelier/photo_digisco/DSC01529.JPG" title="マガンの群れ:沖の州" rel="lightbox[sinjiko]" >マガンの群れ</a><br/>   <a href="http://n-shuhei.net/atelier/photo_digisco/DSC01591.JPG" title="キンクロハジロ?" rel="lightbox[sinjiko]" >キンクロハジロ</a>" lng="133.284674" lat="35.44333" category="num02" /> 
  <marker name="3:宍道湖グリーンパーク" address="   <a href="http://n-shuhei.net/atelier/video/digisco_1.wmv" target="_blank">コハクチョウ(video)</a><br/>   <a href="http://n-shuhei.net/atelier/photo_digisco/DSC01620.JPG" title="セグロセキレイ" rel="lightbox[sinjiko]" >セグロセキレイ</a><br/>   <a href="http://n-shuhei.net/atelier/photo_digisco/DSC01632.JPG" title="トビ?" rel="lightbox[sinjiko]" >トビ</a><br/>   <a href="http://n-shuhei.net/atelier/photo_birds/0911211.jpg" title="ジョウビダキ?" rel="lightbox[sinjiko]" >ジョウビダキ</a><br/>   <a href="http://n-shuhei.net/atelier/photo_drive/DSC_4872.JPG" title="ゴビウスにある水槽" rel="lightbox[sinjiko]">ゴビウスにある水槽</a>" lng="132.866077" lat="35.444729" category="num03" /> 
  <marker name="4:出雲大社" address="   <a href="http://n-shuhei.net/atelier/photo_drive/DSC_4886.JPG" title="出雲大社にて" rel="lightbox[sinjiko]">出雲大社にて</a>" lng="132.685919" lat="35.401434" category="num04" /> 
  <marker name="5:足立美術館" address="   <a href="http://n-shuhei.net/atelier/photo_drive/DSC_4908.JPG" title="足立美術館の紅葉" rel="lightbox[drive]">足立美術館の紅葉</a><br/>   <a href="http://n-shuhei.net/atelier/photo_drive/Stitched_003.JPG" title="枯山水の庭:3枚の合成写真" rel="lightbox[drive]">枯山水の庭</a><br/>   <a href="http://n-shuhei.net/atelier/DSC_4932.JPG" title="足立美術館:絵画を観ているように" rel="lightbox[drive]">仏間から庭を望む</a>" lng="133.198242" lat="35.377854" category="num05" /> 
  <marker name="6:米子自動車道大山PA" address="   <a href="http://n-shuhei.net/atelier/photo_drive/DSC_4720-1.JPG" title="雪化粧した大山:大山PAより" rel="lightbox[sinjiko]">大山の紅葉</a>" lng="133.419342" lat="35.386531" category="num06" /> 
  </markers>


 作成した地図作成の稚拙なHTMLコード(Google Maps API V3 のJavaScript を含む)は、右フレームに掲載している【晩秋の宍道湖私的観光地図】のソース・コードを見ていただければ、わかると思うが、参考までに下に記載し、少しのコメントを加えたいと思う。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 

<title>Google Maps Javascript API v3 Example: Marker Categories</title> 

<!-- jQuery lightbox2.51 -->
<script type="text/javascript" src="http://n-shuhei.net/atelier/Jquery2.51/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://n-shuhei.net/atelier/Jquery2.51/js/lightbox.js"></script>
<link rel="stylesheet" type="text/css" href="http://n-shuhei.net/atelier/Jquery2.51/css/lightbox.css" media="screen" />

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript" src="http://n-shuhei.net/atelier/maps/V3test/downloadxml.js"></script>
    <title>Google Maps</title>
<style type="text/css">
html, body { height: 100%; } 
</style>
    <script type="text/javascript">
    //<![CDATA[
      // this variable will collect the html which will eventually be placed in the side_bar 
      var side_bar_html = ""; 
      var gmarkers = [];
      var gicons = [];
      var map = null;
var infowindow = new google.maps.InfoWindow(
  { 
    size: new google.maps.Size(150,50)
  });

gicons["01"] = new google.maps.MarkerImage("http://n-shuhei.net/Googlemaps/Markers/marker_01.png",
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(20, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 9,34.
      new google.maps.Point(9, 34));
  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.
  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.

  var iconImage = new google.maps.MarkerImage('http://n-shuhei.net/Googlemaps/Markers/marker_01.png',
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(20, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 9,34.
      new google.maps.Point(9, 34));
  var iconShadow = new google.maps.MarkerImage('http://n-shuhei.net/atelier/maps/V3test/msmarker.shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 34),
      new google.maps.Point(0,0),
      new google.maps.Point(9, 34));
 
function getMarkerImage(iconNum) {
   if ((typeof(iconNum)=="undefined") || (iconNum==null)) { 
      iconNum = "01"; 
   }
   if (!gicons[iconNum]) {
      gicons[iconNum] = new google.maps.MarkerImage("http://n-shuhei.net/Googlemaps/Markers/marker_"+ iconNum +".png",
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(20, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 6,20.
      new google.maps.Point(9, 34));
   } 
   return gicons[iconNum];
}

function category2num(category) {
   var num = "01";       
   switch(category) {
     case "num01": num = "01";
                break;
     case "num02": num = "02";
                break;
     case "num03": num = "03";
                break;
     case "num04": num = "04";
                break;
     case "num05": num = "05";
                break;
     case "num06": num = "06";
                break;
     default:   num = "01";
                break;
   }

   return num;
}

      gicons["num01"] = getMarkerImage(category2num("num01"));
      gicons["num02"] = getMarkerImage(category2num("num02"));
      gicons["num03"] = getMarkerImage(category2num("num03"));
      gicons["num04"] = getMarkerImage(category2num("num04"));
      gicons["num05"] = getMarkerImage(category2num("num05"));
      gicons["num06"] = getMarkerImage(category2num("num06"));
      // A function to create the marker and set up the event window
function createMarker(latlng,name,html,category) {
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        icon: gicons[category],
        shadow: iconShadow,
        map: map,
        title: name,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });

        // === Store the category and name info as a marker properties ===
        marker.mycategory = category;                                 
        marker.myname = name;
        gmarkers.push(marker);

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,marker);
        });
}

      // == shows all markers of a particular category, and ensures the checkbox is checked ==
      function show(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].setVisible(true);
          }
        }

        // == check the checkbox ==
        document.getElementById(category+"box").checked = true;
      }

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
      function hide(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].setVisible(false);
          }
        }

        // == clear the checkbox ==
        document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        infowindow.close();
      }

      // == a checkbox has been clicked ==
      function boxclick(box,category) {
        if (box.checked) {
          show(category);
        } else {
          hide(category);
        }

        // == rebuild the side bar
        makeSidebar();
      }

      function myclick(i) {
        google.maps.event.trigger(gmarkers[i],"click");
      }

      // == rebuilds the sidebar to match the markers currently displayed ==
      function makeSidebar() {
        var html = "";
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].getVisible()) {
            html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a>' + ' ' ;
          }
        }

        document.getElementById("side_bar").innerHTML = html;
      }

  function initialize() {
    var myOptions = {
      zoom: 10,
      center: new google.maps.LatLng(35.430603,133.012136),   //松江
      mapTypeId: google.maps.MapTypeId.HYBRID
    }
    map = new google.maps.Map(document.getElementById("map"), myOptions);
    google.maps.event.addListener(map, 'click', function() {
        infowindow.close();
        });

      // Read the data
      downloadUrl("http://n-shuhei.net/atelier/maps/V3_sinnjiko_num.xml", function(doc) {
  var xml = xmlParse(doc);
  var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          // obtain the attribues of each marker
          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var point = new google.maps.LatLng(lat,lng);
          var address = markers[i].getAttribute("address");
          var name = markers[i].getAttribute("name");
          var html = "<b>"+name+"<\/b><p>"+address;
          var category = markers[i].getAttribute("category");
          // create the marker
          var marker = createMarker(point,name,html,category);
        }

        // == create the initial sidebar ==
        makeSidebar();
      });
    }

    //]]>
    </script>
  </head>

<body style="margin:0px; padding:0px;" onload="initialize()"> 
    <!-- you can use tables or divs for the overall layout -->
    <table border=1 >
<tr><td align="center"style="width:1000px; background-color: #ffffe0;" ><br /><h2>晩秋の宍道湖私的観光地図</h2></td></tr>      
<tr><td>
           <div id="map" style="width: 1000px; height: 500px"></div>
        </td></tr><tr>
<td valign="top" style="width:1000px; background-color: #ffffe0; font-size: small;"> 
 上の地図は、Google Mapsの機能を持っています。拡大・縮小・移動ができます。下の該当番号をクリックすると該当番号マーカーに吹きだしが出てきます。その吹き出しにある青文字をクリックすると写真(一部 動画)がでてきます。</td></tr><tr>
        <td valign="top" style="width:1000px; background-color: #ffffe0; font-size: small;"> 
           <div id="side_bar"></div>
        </td>
      </tr>
    </table>


    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>

<br /><br />
<!-- Google AdSense -->
<script type="text/javascript"><!--
google_ad_client = "pub-8556873278052332";
/* AdSense foot ad */
google_ad_slot = "1589991765";
google_ad_width = 728;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
  </body>
</html>


  • 番号付きマーカーは、dLINKbRING というサイトからダウンロードできる
  • 表示する地図を、ラベル付き航空写真とするには、mapTypeId: google.maps.MapTypeId.HYBRID とすればよい。通常は、HYBRID の部分が、ROADMAP となっている。
  • マーカーをクリックしてでる吹きだしの中に表示される写真リンクをクリックして出てくる写真を、同一画面の中央に表示するJavaScript ソフト lightbox は機能する。 jQuerylightbox2.51 を使った。