Google Maps API v3-現在地を取得してそれっぽく表示する-
以下の作業を行います。
- マップを表示
- 現在地取得ボタンをクリックで現在地の緯度経度を取得
- マップの中央を現在地に合わて円を描く
こんな感じになります。
外側の大きな円は取得した現在地の精度によって大きさを決めています。
デモはこちら
Google Maps API v3-現在地を取得してそれっぽく表示する-:デモページ
以下、ソースコードです。
HTML
<button id='currentPosition' >現在地を表示</button> <div id="map_view" style="width: 100%; height: 500px;"></div>
$(function(){ var latLng = new google.maps.LatLng(37,139), mapOptions = { zoom: 12, center: latLng }, map = new google.maps.Map($("#map_view")[0],mapOptions); $("#currentPosition").click(function(){ if (navigator.geolocation) { window.navigator.geolocation.getCurrentPosition( function(result){ //現在地の取得成功 var position = result.coords, radius = position.accuracy, latLng = new google.maps.LatLng(position.latitude, position.longitude), //現在地に大きい円と小さい円を描く bigCircle = { center: latLng, radius: radius, map: map, strokeColor: '#44BBFF', strokeOpacity: 0.2, strokeWeight: 1, fillColor: '#44BBFF', fillOpacity: 0.2 }, smallCircle = { center: latLng, radius: 3, map: map, strokeColor: '#44BBFF', strokeOpacity: 0.8, strokeWeight: 1, fillColor: '#44BBFF', fillOpacity: 0.8 }, circle1 = new google.maps.Circle(bigCircle), circle2 = new google.maps.Circle(smallCircle); //現在地へマップをズームして移動 map.setZoom(16); map.setCenter(latLng); }, function(error){ //取得失敗 alert("エラーが発生しました。"); }, {enableHighAccuracy: true}); } });