座標変換のサンプル


(1)地図をドラッグして、マーカーの位置をずらしてください。
(2)マーカーをクリックすると、その位置にツールチップを表示します。
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
      function init(){
        var mapDiv = document.getElementById("mapDiv");
        mapDiv.style.width = "500px";
        mapDiv.style.height = "500px";
        
        var toolTip = document.createElement("span");
        toolTip.style.position = "absolute";
        toolTip.style.zIndex = 2;
        toolTip.style.padding = "0.2em";
        toolTip.style.backgroundColor = "white";
        toolTip.style.border = "red 1px solid";
        document.getElementsByTagName("body")[0].appendChild(toolTip);
        
        var point = new google.maps.LatLng(35.658609, 139.745447);
        var map = new google.maps.Map(mapDiv, {
          zoom : 8,
          center : point,
          mapTypeId : google.maps.MapTypeId.ROADMAP
        });
        
        var projection = null;
        google.maps.event.addListener(map, "projection_changed", function(){
          projection = map.getProjection();
        });
        
        var marker = createMarker(map, point, "Hello");
        google.maps.event.addListener(marker, "click", function(mouseEvt) {
          //マーカーの緯度経度を世界座標に変換する
          var latLngChoord = projection.fromLatLngToPoint(mouseEvt.latLng);
          
          //地図の左上端を世界座標に変換する
          var bounds = map.getBounds();
          var sw = bounds.getSouthWest();
          var ne = bounds.getNorthEast();
          var nw = new google.maps.LatLng(ne.lat(), sw.lng());
          var nwChoord = projection.fromLatLngToPoint(nw);
          
          //差分を求めて、世界座標をMapDivの座標にする
          var world = Math.pow(2, map.getZoom()); 
          var x = (latLngChoord.x - nwChoord.x)  * world;
          var y = (latLngChoord.y - nwChoord.y)  * world;
          
          //MapDivのオフセット位置を増分
          x += mapDiv.offsetLeft;
          y += mapDiv.offsetTop;
          
          //ツールチップを表示
          toolTip.style.left = x + "px";
          toolTip.style.top = y + "px";
          toolTip.innerText = "(" + x + "px, " + y + "px)";
        });
      }
      function createMarker(map, position, text) {
        var marker = new google.maps.Marker({
          position : position,
          map : map
        });
        return marker;
      }
      window.onload = init;
    </script>
  </head>
  <body>
    <div id="mapDiv"></div>
  </body>
</html>





Search
Books
Google Maps API Programming Guide

Four Google Maps API Experts wrote this book. Introducing useful examples for developers!
See more details