GoogleMapAPI V3で緯度、経度を取得する

Twitter ツイート Hatena Bookmark ブックマーク

JavaScriptがうまく書けないのであまり良い方法ではないと思いますが、一通り動くように書いてみました。
markerの位置の緯度、経度を取得するようにしてあります。
ドラッグ&ドロップやクリックでマーカーが移動して緯度、経度が取得出来るようにしてあります。

だたなんかwindowオブジェクトさわってるのとかどうなの?この書き方かっこわるくね?って思ってたりもします。
だれかJavaScriptを教えてください。。。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var roadGoogleMaps = function(){
	this.latlng;
	this.map;
	this.marker;
};

// marker用のイベント
roadGoogleMaps.makerEvent = function() {
	// markerをドラッグドロップした場合のイベント
	google.maps.event.addListener(this.marker,'dragend',function(event){
		$('#lat').val(event.latLng.lat());
		$('#lng').val(event.latLng.lng());
	});

	// 地図をダブルクリックした際のイベント
	google.maps.event.addListener(this.map,'click',function(event){
		window.roadGoogleMaps.marker.setPosition(event.latLng);
		$('#lat').val(event.latLng.lat());
		$('#lng').val(event.latLng.lng());
	});
}


// map 初期化
roadGoogleMaps.init = function(lat,lng) {
	this.latlng = new google.maps.LatLng(lat,lng);
	this.map =  new google.maps.Map(document.getElementById("map_canvas"), {
		zoom:15,
		center: this.latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});

	this.marker = new google.maps.Marker({
		position: this.latlng,
		draggable: true,
		map: this.map,
		title: "test"
	});
}

html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="javascript">
$(function(){
	roadGoogleMaps.init('35.68406','139.774466');
	roadGoogleMaps.makerEvent();
});
</script>

</head>
<body>
<div id="map_canvas"></div>

緯度:<input type="text" id="lat" value="" name="lat" /><br />
経度: <input  type="text" id="lng" value="" name="lng" >
</body>

</html>
comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。