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

时间:2018-12-05 14:09:36

标签: javascript jquery google-maps

问题是当我搜索位置时,在搜索到的位置上找不到多边形。

下图中的示例。

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

我在此脚本中设置了多边形,并将其设置为默认位置。每当我搜索位置多边形时,都应将其放置在此处,以便我可以将该位置的纬度设置为纬度。 在第二张图片中,我缩小了地图,找到了默认位置的多边形。多边形应移至搜索位置。

in this image I searched location

    <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>

1 个答案:

答案 0 :(得分:1)

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

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);

proof of concept fiddle

screenshot of resulting map after search on "Multan"

代码段:

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>