LoginSignup
7

More than 5 years have passed since last update.

GoogleMapでクリックされた位置を取得するサンプル

Last updated at Posted at 2014-07-23
@{
    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 () {
            google.maps.event.addDomListener(window, 'load', initialize);

            function initialize() {
                var mapOptions = {
                    zoom: 15,
                    center: new google.maps.LatLng(Number($("#latitude").val()), Number($("#longitude").val()))
                };

                var map = new google.maps.Map($("#map-canvas")[0], mapOptions);

                var marker = new google.maps.Marker({
                    position: map.getCenter(),
                    map: map
                });

                google.maps.event.addListener(map, 'click', function (e) {
                    var loc = e.latLng;
                    marker.setPosition(loc);
                    $("#latitude").val(loc.lat());
                    $("#longitude").val(loc.lng());
                });
            }
        });
    </script>
</head>
<body>
    <input id="latitude" type="text" value="33.8391574" />
    <input id="longitude" type="text" value="132.76557520000006" />
    <div id="map-canvas"></div>
</body>
</html>

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
7