LoginSignup
8
9

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-07-23

google.maps.Geocoderを使用して住所や施設名等から位置情報を取得します。

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>住所などから位置を取得する</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
        html, body, #map-canvas {
            height: 500px;
            width: 500px;
            margin: 20px;
            padding: 20px;
        }
    </style>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="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>
    <input id="latitude" type="text" value="33.8391574" />
    <input id="longitude" type="text" value="132.76557520000006" />
    <div id="panel">
        <input id="address" type="text" value="愛媛県松山市">
        <input type="button" value="Geocode" id="geocode">
    </div>
    <div id="map-canvas"></div>
</body>
</html>
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9