首页 > 解决方案 > 如何在搜索到的位置设置多边形?

问题描述

问题是当我搜索一个位置时,我没有得到搜索位置上的多边形。

下图中的示例。

如何在搜索到的位置设置多边形的位置?

我在这个脚本中有多边形,它设置在默认位置。每当我搜索位置多边形时,都应该放在那里,以便我可以设置该位置的纬度。在第二张图片中,我缩小了在默认位置找到多边形的地图。多边形应该移动到搜索到的位置。

在这张图片中我搜索了位置

    <script>
    function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 30.3753, lng: 69.3451},
            zoom: 6,
            mapTypeId: 'roadmap'
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('search_location');
        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,
                    icon: icon,
                    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);
                }

                var arrCoords = [
                    new google.maps.LatLng(32.3753, 64.3451),
                    new google.maps.LatLng(30.3753, 66.3451),
                    new google.maps.LatLng(30.3753, 65.3451),
                    new google.maps.LatLng(29.3753, 63.3451),
                    // new google.maps.LatLng(51.477654, -0.002192)
                ];

                var polygon = new google.maps.Polygon({
                    editable: true,
                    paths: arrCoords,
                    strokeColor: "#FF0000",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#FF0000",
                    fillOpacity: 0.35,
                    map: map,
                    draggable: true,
                    geodesic: true,
                });

                google.maps.event.addListener(polygon, 'dragend', function (evt) {
                    console.log(evt.latLng.lat(), '--', evt.latLng.lng());
                });

                // google.maps.event.addListener(polygon.getPath(), 'insert_at', function(index, obj) {
                //     console.log('Vertex removed from inner path.');
                //     console.log(obj.lat() ,'--',  obj.lng() );
                // });

                google.maps.event.addListener(polygon.getPath(), 'set_at', function (index, obj) {
                    console.log('Vertex moved on outer path.');
                    console.log(obj.lat(), '--', obj.lng());

                    var Array = [];

                    Array.push(obj.lat(), obj.lng(), obj.lat(), obj.lng());

                    $('#lat_long').val(JSON.stringify(Array));

                    var value = $('#lat_long').val();
                    value = JSON.parse(value);
                });


                // Define an info window on the map.
                infoWindow = new google.maps.InfoWindow();
            });


            map.fitBounds(bounds);
        });
    }
  </script>

标签: javascriptjquerygoogle-maps

解决方案


一种选择是移动多边形,使其以自动完成结果返回的坐标为中心:

var polybnds = new google.maps.LatLngBounds();
for (var i = 0; i < polygon.getPath().getLength(); i++) {
  polybnds.extend(polygon.getPath().getAt(i));
}
var polyCenter = polybnds.getCenter();
// center polygon on first marker
var distance = google.maps.geometry.spherical.computeDistanceBetween(polyCenter, markers[0].getPosition());
var heading = google.maps.geometry.spherical.computeHeading(polyCenter, markers[0].getPosition());
var path = [];
polybnds = new google.maps.LatLngBounds();
for (var i = 0; i < polygon.getPath().getLength(); i++) {
  var pt = google.maps.geometry.spherical.computeOffset(polygon.getPath().getAt(i), distance, heading);
  path.push(pt);
  polybnds.extend(pt);
}
polygon.setPath(path);

概念证明小提琴

搜索后结果地图的屏幕截图

代码片段:

html,
body,
#map {
  height: 90%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry&callback=initAutocomplete" async defer></script>
<input id="search_location" />
<div id="map"></div>
<script>
  function initAutocomplete() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {
        lat: 30.3753,
        lng: 69.3451
      },
      zoom: 6,
      mapTypeId: 'roadmap'
    });

    // Create the search box and link it to the UI element.
    var input = document.getElementById('search_location');
    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,
          icon: icon,
          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);
        }

        var arrCoords = [
          new google.maps.LatLng(32.3753, 64.3451),
          new google.maps.LatLng(30.3753, 66.3451),
          new google.maps.LatLng(30.3753, 65.3451),
          new google.maps.LatLng(29.3753, 63.3451),
          // new google.maps.LatLng(51.477654, -0.002192)
        ];

        var polygon = new google.maps.Polygon({
          editable: true,
          paths: arrCoords,
          strokeColor: "#FF0000",
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: "#FF0000",
          fillOpacity: 0.35,
          // map: map,
          draggable: true,
          geodesic: true,
        });
        if (markers.length == 1) { // only do for first marker}
          var polybnds = new google.maps.LatLngBounds();
          for (var i = 0; i < polygon.getPath().getLength(); i++) {
            polybnds.extend(polygon.getPath().getAt(i));
          }
          var polyCenter = polybnds.getCenter();
          // center polygon on first marker
          var distance = google.maps.geometry.spherical.computeDistanceBetween(polyCenter, markers[0].getPosition());
          var heading = google.maps.geometry.spherical.computeHeading(polyCenter, markers[0].getPosition());
          var path = [];
          polybnds = new google.maps.LatLngBounds();
          for (var i = 0; i < polygon.getPath().getLength(); i++) {
            var pt = google.maps.geometry.spherical.computeOffset(polygon.getPath().getAt(i), distance, heading);
            path.push(pt);
            polybnds.extend(pt);
          }
          polygon.setPath(path);
          polygon.setMap(map);
          google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
            map.fitBounds(polybnds);
          });
        }
        google.maps.event.addListener(polygon, 'dragend', function(evt) {
          console.log(evt.latLng.lat(), '--', evt.latLng.lng());
        });

        google.maps.event.addListener(polygon.getPath(), 'set_at', function(index, obj) {
          console.log('Vertex moved on outer path.');
          console.log(obj.lat(), '--', obj.lng());

          var Array = [];

          Array.push(obj.lat(), obj.lng(), obj.lat(), obj.lng());

          $('#lat_long').val(JSON.stringify(Array));

          var value = $('#lat_long').val();
          value = JSON.parse(value);
        });


        // Define an info window on the map.
        infoWindow = new google.maps.InfoWindow();
      });
      map.fitBounds(bounds);
    });
  }
</script>


推荐阅读