【问题标题】:Fetch JSON from Google Maps Autocomplete and Submit it into Django Form Data从 Google Maps Autocomplete 获取 JSON 并将其提交到 Django 表单数据中
【发布时间】:2019-08-04 20:54:17
【问题描述】:

对于我的网站,我想在页面中放置一个谷歌地图自动完成表单,当用户提交坐标时,会将 JSON 发送到 Django 表单,以便它可以将其提交到数据库中。

我唯一的问题是我不知道如何从谷歌地图应用程序中获取纬度和经度,并将其提交到 Django。

这是 Google 地图自动完成的代码:

<html>
    <head>
        <title>Place Autocomplete</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
            /* Always set the map height explicitly to define the size of the div
            * element that contains the map. */
            #map {
            height: 100%;
            }
            /* Optional: Makes the sample page fill the window. */
            html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            }
            #description {
            font-family: Roboto;
            font-size: 15px;
            font-weight: 300;
            }
            #infowindow-content .title {
            font-weight: bold;
            }
            #infowindow-content {
            display: none;
            }
            #map #infowindow-content {
            display: inline;
            }
            .pac-card {
            margin: 10px 10px 0 0;
            border-radius: 2px 0 0 2px;
            box-sizing: border-box;
            -moz-box-sizing: border-box;
            outline: none;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
            background-color: #fff;
            font-family: Roboto;
            }
            #pac-container {
            padding-bottom: 12px;
            margin-right: 12px;
            }
            .pac-controls {
            display: inline-block;
            padding: 5px 11px;
            }
            .pac-controls label {
            font-family: Roboto;
            font-size: 13px;
            font-weight: 300;
            }
            #pac-input {
            background-color: #fff;
            font-family: Roboto;
            font-size: 15px;
            font-weight: 300;
            margin-left: 12px;
            padding: 0 11px 0 13px;
            text-overflow: ellipsis;
            width: 400px;
            }
            #pac-input:focus {
            border-color: #4d90fe;
            }
            #title {
            color: #fff;
            background-color: #4d90fe;
            font-size: 25px;
            font-weight: 500;
            padding: 6px 12px;
            }
        </style>
    </head>
    <body>
        <div class="pac-card" id="pac-card">
            <div>
                <div id="title">
                    Autocomplete search
                </div>
                <div id="type-selector" class="pac-controls">
                    <input type="radio" name="type" id="changetype-all" checked="checked">
                    <label for="changetype-all">All</label>
                    <input type="radio" name="type" id="changetype-establishment">
                    <label for="changetype-establishment">Establishments</label>
                    <input type="radio" name="type" id="changetype-address">
                    <label for="changetype-address">Addresses</label>
                    <input type="radio" name="type" id="changetype-geocode">
                    <label for="changetype-geocode">Geocodes</label>
                </div>
                <div id="strict-bounds-selector" class="pac-controls">
                    <input type="checkbox" id="use-strict-bounds" value="">
                    <label for="use-strict-bounds">Strict Bounds</label>
                </div>
            </div>
            <div id="pac-container">
                <input id="pac-input" type="text"
                    placeholder="Enter a location">
            </div>
        </div>
        <div id="map"></div>
        <div id="infowindow-content">
            <img src="" width="16" height="16" id="place-icon">
            <span id="place-name"  class="title"></span><br>
            <span id="place-address"></span>
        </div>
        <script>
            // This example requires the Places library. Include the libraries=places
            // parameter when you first load the API. For example:
            // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
            function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
              center: {
                  lat: 21.3000,
                  lng: 202.1460
              },
              zoom: 13
            });
            var placeMarker = {} //gets updated lat lng from the marker
            var card = document.getElementById('pac-card');
            var input = document.getElementById('pac-input');
            var types = document.getElementById('type-selector');
            var strictBounds = document.getElementById('strict-bounds-selector');

            map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

            var autocomplete = new google.maps.places.Autocomplete(input);

            // Bind the map's bounds (viewport) property to the autocomplete object,
            // so that the autocomplete requests use the current map bounds for the
            // bounds option in the request.
            autocomplete.bindTo('bounds', map);

            // Set the data fields to return when the user selects a place.
            autocomplete.setFields(
              ['address_components', 'geometry', 'icon', 'name']);
            var myLatlng = new google.maps.LatLng(21.307, -157.858); //sets marker to honolulu
            var infowindow = new google.maps.InfoWindow();
            var infowindowContent = document.getElementById('infowindow-content');
            infowindow.setContent(infowindowContent);
            var marker = new google.maps.Marker({
              map: map,
              position: myLatlng,
              draggable: true,
              anchorPoint: new google.maps.Point(0, -29)
            });

            google.maps.event.addListener(marker, 'dragend', function(evt) {
            placeMarker['lat'] = evt.latLng.lat()
            placeMarker['lng'] = evt.latLng.lng()
              console.log(placeMarker);
            });

            autocomplete.addListener('place_changed', function() {
              infowindow.close();
              marker.setVisible(true);
              var place = autocomplete.getPlace();
              if (!place.geometry) {
                  // User entered the name of a Place that was not suggested and
                  // pressed the Enter key, or the Place Details request failed.
                  window.alert("No details available for input: '" + place.name + "'");
                  return;
              }

              // If the place has a geometry, then present it on a map.
              if (place.geometry.viewport) {
                  map.fitBounds(place.geometry.viewport);
              } else {
                  map.setCenter(place.geometry.location);
                  map.setZoom(17); // Why 17? Because it looks good.
              }
              marker.setPosition(place.geometry.location);
              marker.setVisible(true);
            var placeMarker = {}
              //gets position of marker when they type in a location
            placeMarker['lat'] = marker.getPosition().lat()
            placeMarker['lng'] = marker.getPosition().lat()
              console.log(placeMarker);

              var address = '';
              if (place.address_components) {
                  address = [
                      (place.address_components[0] && place.address_components[0].short_name || ''),
                      (place.address_components[1] && place.address_components[1].short_name || ''),
                      (place.address_components[2] && place.address_components[2].short_name || '')
                  ].join(' ');
              }

              infowindowContent.children['place-icon'].src = place.icon;
              infowindowContent.children['place-name'].textContent = place.name;
              infowindowContent.children['place-address'].textContent = address;
              infowindow.open(map, marker);
            });

            // Sets a listener on a radio button to change the filter type on Places
            // Autocomplete.
            function setupClickListener(id, types) {
              var radioButton = document.getElementById(id);
              radioButton.addEventListener('click', function() {
                  autocomplete.setTypes(types);
              });
            }

            setupClickListener('changetype-all', []);
            setupClickListener('changetype-address', ['address']);
            setupClickListener('changetype-establishment', ['establishment']);
            setupClickListener('changetype-geocode', ['geocode']);

            document.getElementById('use-strict-bounds')
              .addEventListener('click', function() {
                  console.log('Checkbox clicked! New state=' + this.checked);
                  autocomplete.setOptions({
                      strictBounds: this.checked
                  });
              });
            }
            //get directions part will use this link 
            //https://www.google.com/maps/dir//21.307,-157.858/@21.4297802,-158.1141956,10.83z
            //last half is the zoom settings; first 2 numbs are lat long.
        </script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAzjwfZHvAzrcCsD7NOXkvgMmQmzxDQPBU&libraries=places&callback=initMap"
            async defer></script>
    </body>
</html>

以下是 Google 地图自动完成的示例:https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete

我在代码中添加了字典“placeMarker”并插入了纬度和经度,认为有某种方法可以将对象获取到 Django。而且我知道一旦表单提交,Django就可以获取表单数据。

如果您需要更多信息,请随时询问。

感谢您的宝贵时间!

【问题讨论】:

    标签: javascript json django google-maps fetch


    【解决方案1】:

    纬度和经度在place.geometry.location对象内,也许你可以把它放到var中并根据你的需要使用。

    【讨论】:

      猜你喜欢
      • 2018-10-27
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多