Quantcast
Channel: なか日記
Viewing all articles
Browse latest Browse all 848

GoogleMapで住所などから位置を取得して表示する

$
0
0

この前投稿したやつに関連して

前回ので自分でマップをクリックして位置情報が取れるようになりましたが、予め住所や施設名がわかっている場合はそれを入力してサクッと位置を特定したいですよね。

画面サンプル

f:id:nakaji999:20140724013149p:plain

コードサンプル

前回のコードは引き継いでません。

@{
    Layout = null;
}

<!DOCTYPE html><html><head><title>住所などから位置を取得する</title><metaname="viewport"content="initial-scale=1.0, user-scalable=no"><metacharset="utf-8"><style>html, body, #map-canvas{height: 500px;
            width: 500px;
            margin: 20px;
            padding: 20px;
        }</style><scriptsrc="~/Scripts/jquery-1.10.2.js"></script><scriptsrc="https://maps.googleapis.com/maps/api/js?v=3.exp"></script><script>        $(function(){var map;var marker;var geocoder;            google.maps.event.addDomListener(window, 'load', initialize);function initialize(){var mapOptions = {                    zoom: 15,                    center: new google.maps.LatLng(Number($("#latitude").val()), Number($("#longitude").val()))
};                map = new google.maps.Map($("#map-canvas")[0], mapOptions);                marker = new google.maps.Marker({                    position: map.getCenter(),                    map: map});                geocoder = new google.maps.Geocoder();}            $("#geocode").click(
function(){var address = $("#address").val();                    geocoder.geocode({'address': address }, function(results, status){if(status == google.maps.GeocoderStatus.OK){var loc = results[0].geometry.location;                            map.setCenter(loc);                            marker.setPosition(loc);                            $("#latitude").val(loc.lat());                            $("#longitude").val(loc.lng());}else{alert('Geocode was not successful for the following reason: ' + status);}});});});</script></head><body><inputid="latitude"type="text"value="33.8391574" /><inputid="longitude"type="text"value="132.76557520000006" /><divid="panel"><inputid="address"type="text"value="愛媛県松山市"><inputtype="button"value="Geocode"id="geocode"></div><divid="map-canvas"></div></body></html>

Geocoderクラスのgeocodeメソッドを使用するのがポイントですね。


Viewing all articles
Browse latest Browse all 848

Trending Articles