根据选择的输入地址和半径显示Google地图

时间:2018-08-29 16:38:55

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

我需要根据文本框中输入的地址和从Miles下拉列表中选择的半径范围显示地图。 假设我在文本框中输入 NewYork,NY,USA ,然后从“英里数”下拉列表中选择 50英里之类的值,则我的地图应显示50英里的纽约范围。

打开地图时默认为默认值,我正在传递默认中心值。在文本框中输入地址后,我需要将输入的文本框位置传递到代码中以获取地图。我该怎么办?

这是我的代码:

var METERS_PER_MILE = 1609.34;

function myMap() {
  var myCenter = new google.maps.LatLng(56.1304, -106.3468);
  var mapProp = {
    center: myCenter,
    zoom: 6,
    scrollwheel: true,
    draggable: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map"), mapProp);
  var circle;
  google.maps.event.addDomListener(document.getElementById('range'), 'change', function(evt) {
    var value = $("#range").val();
    if (circle && circle.setMap) circle.setMap(null);
    circle = new google.maps.Circle({
      center: myCenter,
      radius: value * METERS_PER_MILE,
      map: map
    });
    map.fitBounds(circle.getBounds());
  });
}
google.maps.event.addDomListener(window, 'load', myMap);

           //Autocomplete address search

            // Create the search box and link it to the UI element.
            var input = document.getElementById('searchtext');
            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) {
                    if (!place.geometry) {
                        console.log("Returned place contains no geometry");
                        return;
                    }
                    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,
                        animation: google.maps.Animation.DROP,
                        title: place.name,
                        position: place.geometry.location
                    }));

                    if (place.geometry.viewport) {
                        // Only geocodes have viewport.
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }
                });
                map.fitBounds(bounds);
            });
<div id="map" style="height: 100%; width: 100%; position: absolute; top: 0px; left: 0px; "></div>

<input id="searchtext" type="text" value=" " class="search-text controls" placeholder="Enter your search location here" style="z-index: 0; position: absolute; left: 125px; top: 0px;">

<div id="searchcontainer" style="position: absolute; z-index: 0; left: 450px; top: 0px;">
    <select id="range" name="range">
        <option value="0">Current Map</option>
        <option value="5">5 Miles</option>
        <option value="10">10 Miles</option>
        <option value="15">15 Miles</option>
        <option value="20">20 Miles</option>
        <option value="25">25 Miles</option>
        <option value="50">50 Miles</option>
        <option value="100">100 Miles</option>
        <option value="250">250 Miles</option>
        <option value="500">500 Miles</option>
    </select>

</div>

1 个答案:

答案 0 :(得分:1)

我相信这就是您想要的:

  1. 当用户在“自动完成”下拉菜单中选择一个条目时,将地图居中并缩放以显示一个半径在下拉列表中选择的圆。
  2. 当用户在范围下拉列表中选择一个条目时,更新圆的大小(从自动完成下拉列表中选择当前位置周围,或者如果未选择则显示地图中心)

为此,请更新range下拉更改侦听器:

google.maps.event.addDomListener(document.getElementById('range'), 'change', function(evt) {
  // make the radius of the circle depend on the dropdown
  var value = $("#range").val();
  if (circle && circle.setMap) circle.setMap(null);
  // default center on the map's center
  var center = map.getCenter();
  // if a marker exists, center on it.
  if (markers.length > 0) center = markers[0].getPosition();
  circle = new google.maps.Circle({
    center: center,
    radius: value * METERS_PER_MILE,
    map: map
  });
  map.fitBounds(circle.getBounds());
});

要以自动完成的结果为中心居中并缩放地图以使其适合范围下拉列表所指定的圆圈:

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) {
    if (!place.geometry) {
      console.log("Returned place contains no geometry");
      return;
    }
    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,
      animation: google.maps.Animation.DROP,
      title: place.name,
      position: place.geometry.location
    }));

    if (place.geometry.viewport) {
      // Only geocodes have viewport.
      bounds.union(place.geometry.viewport);
    } else {
      bounds.extend(place.geometry.location);
    }
    if (circle && circle.setMap) circle.setMap(null);
    var value = $("#range").val();
    circle = new google.maps.Circle({
      center: place.geometry.location,
      radius: value * METERS_PER_MILE,
      map: map
    });
    map.fitBounds(circle.getBounds());
  });
  map.fitBounds(bounds);
});

(请注意,如果有多个结果,则此代码会将地图/圆圈居于最后一个结果的中心)

proof of concept fiddle

screenshot of resulting map

代码段:

var METERS_PER_MILE = 1609.34;

function myMap() {
  var myCenter = new google.maps.LatLng(56.1304, -106.3468);
  var mapProp = {
    center: myCenter,
    zoom: 6,
    scrollwheel: true,
    draggable: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map"), mapProp);
  var circle;
  google.maps.event.addDomListener(document.getElementById('range'), 'change', function(evt) {
    var value = $("#range").val();
    if (circle && circle.setMap) circle.setMap(null);
    var center = map.getCenter();
    if (markers.length > 0) center = markers[0].getPosition();
    circle = new google.maps.Circle({
      center: center,
      radius: value * METERS_PER_MILE,
      map: map
    });
    map.fitBounds(circle.getBounds());
  });
  //Autocomplete address search

  // Create the search box and link it to the UI element.
  var input = document.getElementById('searchtext');
  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) {
      if (!place.geometry) {
        console.log("Returned place contains no geometry");
        return;
      }
      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,
        animation: google.maps.Animation.DROP,
        title: place.name,
        position: place.geometry.location
      }));

      if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
      } else {
        bounds.extend(place.geometry.location);
      }
      if (circle && circle.setMap) circle.setMap(null);
      var value = $("#range").val();
      circle = new google.maps.Circle({
        center: place.geometry.location,
        radius: value * METERS_PER_MILE,
        map: map
      });
      map.fitBounds(circle.getBounds());
    });
    map.fitBounds(bounds);
  });

}
google.maps.event.addDomListener(window, 'load', myMap);
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map"></div>

<input id="searchtext" type="text" value=" " class="search-text controls" placeholder="Enter your search location here" style="z-index: 0; position: absolute; left: 125px; top: 0px;">

<div id="searchcontainer" style="position: absolute; z-index: 0; left: 450px; top: 0px;">
  <select id="range" name="range">
    <option value="0">Current Map</option>
    <option value="5">5 Miles</option>
    <option value="10">10 Miles</option>
    <option value="15">15 Miles</option>
    <option value="20">20 Miles</option>
    <option value="25">25 Miles</option>
    <option value="50">50 Miles</option>
    <option value="100">100 Miles</option>
    <option value="250">250 Miles</option>
    <option value="500">500 Miles</option>
  </select>

</div>