スポンサードリンク

ポリライン polylineを簡単に地図の中に書くためにエンコード化する方法とツール

地図をクリックして、エンコード化されたポリラインを貼り付ける方法が、地図に線を描く方法としては便利そうです。

今回は、そのポリラインをエンコード化する方法ためのツールとして、Google先生のデモマップをいじって自分好みに使いやすいように直しておきます。

 

地図をクリックしてポリラインを描いた後にアイコンを移動させたり、削除しても逐一エンコードされたポリラインが表示されるように変更してみました。

 

1.ソース

<script type="text/javascript">
var poly, map;
var markers = [];
var path = new google.maps.MVCArray;
var centre = new google.maps.LatLng(35.590319,139.739176);

function initialize() 
{
	map = new google.maps.Map(document.getElementById("map"), 
	{
	zoom: 10,
	center: centre,
	mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	var polyOptions = 
	{
	strokeColor: '#000000',
        strokeOpacity: 1.0,
        strokeWeight: 3,
        map: map
        };

        poly = new google.maps.Polyline(polyOptions);
	poly.setMap(map);

	google.maps.event.addListener(map, 'click', addPoint);
}

function addPoint(event) 
{
	var path = poly.getPath();
	path.push(event.latLng);

        var encodeString = google.maps.geometry.encoding.encodePath(path);
        if (encodeString) 
	{
        document.getElementById('encoded-polyline').value = encodeString;
        }
	
	var marker = new google.maps.Marker(
	{
      	position: event.latLng,
      	map: map,
      	draggable: true,
   	title: '移動できます',
   	icon: "http://labs.google.com/ridefinder/images/mm_20_blue.png"
    	});
	
    	markers.push(marker);
    	marker.setTitle("#" + path.length);

    	google.maps.event.addListener(marker, 'click', function() 
	{
      	marker.setMap(null);
      	for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
      	markers.splice(i, 1);
      	path.removeAt(i);
        var encodeString = google.maps.geometry.encoding.encodePath(path);
        	if (encodeString) 
		{
        	document.getElementById('encoded-polyline').value = encodeString;
        	}

      	});

    	google.maps.event.addListener(marker, 'dragend', function() 
	{
      	for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
      	path.setAt(i, marker.getPosition());
        var encodeString = google.maps.geometry.encoding.encodePath(path);
        	if (encodeString) 
		{
        	document.getElementById('encoded-polyline').value = encodeString;
        	}
      	});
}
window.onload = initialize;

</script>

 

 

2.完成サンプルデモ

 

◆Google Maps JavaScript API V3 デベロッパーガイド

◆Google Maps JavaScript API V3

 

スポンサードリンク

Related Posts

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <img localsrc="" alt="">