找到lat&来自标记的lng,带有自动完成搜索框

时间:2016-06-01 09:53:02

标签: javascript google-maps google-maps-api-3

<!DOCTYPE html>
<html>

<head>
  <title>GLANCE</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <style>
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    #map {
      height: 70%;
    }
    .controls {
      margin-top: 10px;
      border: 1px solid transparent;
      border-radius: 2px 0 0 2px;
      box-sizing: border-box;
      -moz-box-sizing: border-box;
      height: 32px;
      outline: none;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    }
    #pac-input {
      background-color: #000000;
      font-family: Roboto;
      font-size: 15px;
      font-weight: 300;
      margin-left: 12px;
      padding: 0 11px 0 13px;
      text-overflow: ellipsis;
      width: 300px;
    }
    #pac-input:focus {
      border-color: #4d90fe;
    }
    .pac-container {
      font-family: Roboto;
    }
    #type-selector {
      color: #000000;
      background-color: #4d90fe;
      padding: 5px 11px 0px 11px;
    }
    #type-selector label {
      font-family: Roboto;
      font-size: 13px;
      font-weight: 300;
    }
    #target {
      width: 345px;
    }
  </style>
</head>

<body>
  <input id="pac-input" class="controls" type="text" placeholder="Digita Località">
  <div id="map"></div>
  <script>
    // This example adds a search box to a map, using the Google Place Autocomplete
     // feature. People can enter geographical searches. The search box will return a
     // pick list containing a mix of places and predicted search terms.

     // 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">
    var marker;
    var xlat;
    var xlon;

    function initAutocomplete() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {
          lat: 44.689205,
          lng: 10.663778
        },
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          map.setCenter(initialLocation);
          xlat = position.coords.latitude;
          xlon = position.coords.longitude;

          marker = new google.maps.Marker({
            icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            }

          });
          marker.addListener('click', toggleBounce);
        });


      }

      // Create the search box and link it to the UI element.
      var input = document.getElementById('pac-input');
      var searchBox = new google.maps.places.SearchBox(input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

      // Bias the SearchBox results towards current map's viewport.
      map.addListener('bounds_changed', function() {
        searchBox.setBounds(map.getBounds());
      });


      var markers = [];
      // Listen for the event fired when the user selects a prediction and retrieve
      // more details for that place.
      searchBox.addListener('places_changed', function() {
        var places = searchBox.getPlaces();

        if (places.length == 0) {
          return;
        }

        // Clear out the old markers.
        markers.forEach(function(marker) {
          marker.setMap(null);
        });
        markers = [];

        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function(place) {


          var icon = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
          };

          // Create a marker for each place.
          markers.push(new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: place.geometry.location
              // var xlat = place.geometry.location.lat();
              // var xlon = place.geometry.location.lon();
          }));




          if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
          } else {
            bounds.extend(place.geometry.location);
          }
        });
        map.fitBounds(bounds);
      });
    }


    function vai() {
      window.location = "listadomande.jsp?lat=" + xlat + "&lon=" + xlon;
    }
  </script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDho6YqRH605Poc-S0AcShQu4hLYDUMGpk&libraries=places&callback=initAutocomplete" async defer></script>
  <footer id="footer">

    <br>
    <ul class="actions">
      <li>
        <p onclick="vai()" class="button big">INVIA</p>
      </li>
    </ul>
  </footer>

</body>

</html>

我成功找到了我命名为xlat&amp; amp;的初始点的坐标。 xlon(地理定位),但是当我搜索另一个地方时,我不知道如何改变这个xlat和xlon。我尝试使用xlat = place.geometry.location.lat(); xlon = place.geometry.location.lon();但当我把这些地图消失=( {{3}}

`var marker;
   var xlat;
   var xlon;
      function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 44.689205, lng: 10.663778},
          zoom: 14,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(initialLocation);
                xlat = position.coords.latitude;
                xlon = position.coords.longitude;

                marker = new google.maps.Marker({
                    icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
                    map: map,
                    draggable: true,
                    animation: google.maps.Animation.DROP,
                    position: {lat: position.coords.latitude, lng: position.coords.longitude}

                });
                  marker.addListener('click', toggleBounce);
            });


            }

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
          searchBox.setBounds(map.getBounds());
        });


        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
          var places = searchBox.getPlaces();

          if (places.length == 0) {
            return;
          }

          // Clear out the old markers.
          markers.forEach(function(marker) {
            marker.setMap(null);
          });
          markers = [];

          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
          places.forEach(function(place) {


            var icon = {
              url: place.icon,
              size: new google.maps.Size(71, 71),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(17, 34),
              scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            markers.push(new google.maps.Marker({
                map: map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: place.geometry.location
           **xlat = place.geometry.location.lat();
             xlon = place.geometry.location.lon();**
            }));




            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });
 }


    function go(){
        window.location="get.jsp?lat="+xlat+"&lon="+xlon;
    }`

2 个答案:

答案 0 :(得分:1)

我认为这里的解决方案可能不是将xlat和xlong设置为Javascript代码中的变量,而是将它们作为隐藏元素包含在页面上,并在返回纬度和经度时设置值。因此,例如,在您的HTML代码中,放置类似这样的内容

<div id="xlat" data-attr-val="" ></div>
<div id="xlong" data-attr-val="" ></div>

然后当您返回经度和纬度值时,可以替换这些行

**xlat = place.geometry.location.lat();
 xlon = place.geometry.location.lon();**

使用:

document.getElementById('xlat').setAttribute("data-attr-val", place.geometry.location.lat());
document.getElementById('xlong').setAttribute("data-attr-val", place.geometry.location.lon());

然后当你想调用函数vai()时,你可以使用这个

function vai() {
    lat = document.getElementById('xlat').getAttribute("data-attr-val");
    lng = document.getElementById('xlng').getAttribute("data-attr-val");
    window.location = "listadomande.jsp?lat=" + lat + "&lon=" + lng;
}

答案 1 :(得分:0)

此代码存在一些问题。请看这部分:

markers.push(new google.maps.Marker({ map: map, draggable: true, animation: google.maps.Animation.DROP, position: place.geometry.location var xlat = place.geometry.location.lat(); var xlon = place.geometry.location.lon(); }));

  1. 您尝试在作为标记选项传递的对象内定义变量xlat和xlon。您应该将这些变量放在对象之外。
  2. 此外,您已在initAutocomplete()函数之外定义了变量xlat和xlon,因此无需再次使用var
  3. LatLng类的Maps JavaSript API没有lon()方法,它有lng()方法:https://developers.google.com/maps/documentation/javascript/reference?hl=en#LatLng
  4. 所以你的代码应该是

    markers.push(new google.maps.Marker({ map: map, draggable: true, animation: google.maps.Animation.DROP, position: place.geometry.location })); xlat = place.geometry.location.lat(); xlon = place.geometry.location.lng();

    您可以在http://jsbin.com/nojima/edit?html,output

    看到修改后的版本