Google 将位置映射到具有不同边界的屏幕

Google maps fit location to screen with different bounds

首先,我一直在网上查看,但找不到答案。

我将自动完成与 goole 地图相结合,如果用户需要,he/she 也可以移动标记,我可以从中获取地址。您可以在下面找到代码。

当用户搜索例如法国尼斯时,是否可以将尼斯从例如边界匹配到我的地图?也许我必须动态更改缩放或者我需要设置新的视口,我不确定。到目前为止我发现的是,我可以给出一个距离并创建一个圆来使该圆适合视口。但是圆的半径是固定的,所以它可以适合尼斯但不能适合迈阿密。

希望我能解释一下我的意思。提前谢谢你。

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style>
            #map_canvas {
                width: 980px;
                height: 500px;
            }
            #current {
                padding-top: 5px;
            }
        </style>
    </head>
    <body>
        <label>Enter address:</label><br>
        <input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
        <section>
            <div id='map_canvas' style=""></div>
            <div id="current">No info...</div>
        </section>

        <div style="margin-top: 10px;" id="data_area">

        </div>

        <script>
            function initMap() {
                var map = new google.maps.Map(document.getElementById('map_canvas'), {
                    zoom: 10,
                    center: new google.maps.LatLng(41.0082, 28.9784),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                });

                var myMarker = new google.maps.Marker({
                    position: new google.maps.LatLng(41.0082, 28.9784),
                    draggable: true
                });
                var geocoder = new google.maps.Geocoder;
                var markers = [];
                markers.push(myMarker);

                var input = document.getElementById('searchTextField');
                var autocomplete = new google.maps.places.Autocomplete(input);

                map.addListener('idle', function() {
                    console.log(map.getBounds());
                    var bounds = map.getBounds();
                    var ne = bounds.getNorthEast();
                    var sw = bounds.getSouthWest();


                });

                google.maps.event.addListener(autocomplete, 'place_changed', function () {
                    for (var i = 0; i < markers.length; i++) {
                        markers[i].setMap(null);
                    }
                    markers = [];

                    var place = autocomplete.getPlace();

                    var myMarker = new google.maps.Marker({
                        position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
                        draggable: true
                    });

                    markers.push(myMarker);
                    map.setCenter(myMarker.position);
                    myMarker.setMap(map);

                    google.maps.event.clearListeners(myMarker, 'dragend');
                    google.maps.event.clearListeners(myMarker, 'dragstart');

                    drag(myMarker, geocoder, map);

                }); 

                drag(myMarker, geocoder, map);

                map.setCenter(myMarker.position);
                myMarker.setMap(map);
            }

            function drag(myMarker, geocoder, map) {
                geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
                google.maps.event.addListener(myMarker, 'dragend', function (evt) {
                    document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
                    geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
                });

                google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
                    document.getElementById('current').innerHTML = '<p>Waiting...</p>';
                });
            }
            function geocodeLatLng(geocoder, map, lat, lng) {
                var input = lat + "," + lng;
                var latlngStr = input.split(',', 2);
                var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
                geocoder.geocode({'location': latlng}, function(results, status) {
                  if (status === 'OK') {
                    if (results[0]) {
                        console.log(results[0])
                      var data_arr = []



                      document.getElementById("data_area").innerHTML = "";

                      var data_country = results[0].address_components.find(function(element) { 
                        return element.types[0] == "country"; 
                      }); 
                      var data_administrative_1 = results[0].address_components.find(function(element) { 
                        return element.types[0] == "administrative_area_level_1"; 
                      }); 
                      var data_administrative_2 = results[0].address_components.find(function(element) { 
                        return element.types[0] == "administrative_area_level_2"; 
                      }); 
                      var data_administrative_3 = results[0].address_components.find(function(element) { 
                        return element.types[0] == "administrative_area_level_3"; 
                      }); 
                      var data_administrative_4 = results[0].address_components.find(function(element) { 
                        return element.types[0] == "administrative_area_level_4"; 
                      }); 
                      var data_route = results[0].address_components.find(function(element) { 
                        return element.types[0] == "route"; 
                      }); 

                      if (data_route !== undefined) {data_arr.push(data_route["long_name"]);}
                      if (data_administrative_4 !== undefined) {data_arr.push(data_administrative_4["long_name"]);}
                      if (data_administrative_3 !== undefined) {data_arr.push(data_administrative_3["long_name"]);}
                      if (data_administrative_2 !== undefined) {data_arr.push(data_administrative_2["long_name"]);}
                      if (data_administrative_1 !== undefined) {data_arr.push(data_administrative_1["long_name"]);}
                      if (data_country !== undefined) {data_arr.push(data_country["long_name"]);}

                        data_arr.forEach(function(data) { 
                            var node = document.createElement("LI"); 
                            var textnode = document.createTextNode(data);
                            node.appendChild(textnode);
                            document.getElementById("data_area").appendChild(node);
                        });
                    } else {
                      window.alert('No data!');
                    }
                  } else {
                    window.alert('Geocoder failed: ' + status);
                  }
                });
            }

        </script>

        <script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_API_KEY&callback=initMap"></script>

    </body>
</html> 

Autocomplete 服务 returns 所选位置的几何形状,缩放地图以显示这些边界(在 fiddle/snippet 我添加了一个矩形以显示返回的边界,如果你不想显示它,删除它):

  var place = autocomplete.getPlace();
  if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);
  } else if (place.geometry.bounds) {
    map.fitBounds(place.geometry.bounds);
  } 

proof of concept fiddle

html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

#map_canvas {
  width: 100%;
  height: 80%;
}

#current {
  padding-top: 5px;
}
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section style="width: 100%; height:100%;">
  <div id='map_canvas' style=""></div>
  <div id="current">No info...</div>
</section>

<div style="margin-top: 10px;" id="data_area"></div>

<script>
  var rect;
  var map;

  function initMap() {
    map = new google.maps.Map(document.getElementById('map_canvas'), {
      zoom: 10,
      center: new google.maps.LatLng(41.0082, 28.9784),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var myMarker = new google.maps.Marker({
      position: new google.maps.LatLng(41.0082, 28.9784),
      draggable: true
    });
    var geocoder = new google.maps.Geocoder;
    var markers = [];
    markers.push(myMarker);

    var input = document.getElementById('searchTextField');
    var autocomplete = new google.maps.places.Autocomplete(input);

    map.addListener('idle', function() {
      console.log(map.getBounds());
      var bounds = map.getBounds();
      var ne = bounds.getNorthEast();
      var sw = bounds.getSouthWest();
    });

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
      }
      markers = [];

      var place = autocomplete.getPlace();
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
        if (rect && rect.setMap) rect.setMap(null);
        rect = new google.maps.Rectangle({
          map: map,
          bounds: place.geometry.viewport
        })
      } else if (place.geometry.bounds) {
        map.fitBounds(place.geometry.bounds);
        if (rect && rect.setMap) rect.setMap(null);
        rect = new google.maps.Rectangle({
          map: map,
          bounds: place.geometry.bounds
        })
      }
      var myMarker = new google.maps.Marker({
        position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
        draggable: true
      });

      markers.push(myMarker);
      map.setCenter(myMarker.position);
      myMarker.setMap(map);

      google.maps.event.clearListeners(myMarker, 'dragend');
      google.maps.event.clearListeners(myMarker, 'dragstart');

      drag(myMarker, geocoder, map);

    });

    drag(myMarker, geocoder, map);

    map.setCenter(myMarker.position);
    myMarker.setMap(map);
  }

  function drag(myMarker, geocoder, map) {
    geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
    google.maps.event.addListener(myMarker, 'dragend', function(evt) {
      document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
      geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
    });

    google.maps.event.addListener(myMarker, 'dragstart', function(evt) {
      document.getElementById('current').innerHTML = '<p>Waiting...</p>';
    });
  }

  function geocodeLatLng(geocoder, map, lat, lng) {
    var input = lat + "," + lng;
    var latlngStr = input.split(',', 2);
    var latlng = {
      lat: parseFloat(latlngStr[0]),
      lng: parseFloat(latlngStr[1])
    };
    geocoder.geocode({
      'location': latlng
    }, function(results, status) {
      if (status === 'OK') {
        if (results[0]) {
          console.log(results[0])
          var data_arr = []

          document.getElementById("data_area").innerHTML = "";

          var data_country = results[0].address_components.find(function(element) {
            return element.types[0] == "country";
          });
          var data_administrative_1 = results[0].address_components.find(function(element) {
            return element.types[0] == "administrative_area_level_1";
          });
          var data_administrative_2 = results[0].address_components.find(function(element) {
            return element.types[0] == "administrative_area_level_2";
          });
          var data_administrative_3 = results[0].address_components.find(function(element) {
            return element.types[0] == "administrative_area_level_3";
          });
          var data_administrative_4 = results[0].address_components.find(function(element) {
            return element.types[0] == "administrative_area_level_4";
          });
          var data_route = results[0].address_components.find(function(element) {
            return element.types[0] == "route";
          });

          if (data_route !== undefined) {
            data_arr.push(data_route["long_name"]);
          }
          if (data_administrative_4 !== undefined) {
            data_arr.push(data_administrative_4["long_name"]);
          }
          if (data_administrative_3 !== undefined) {
            data_arr.push(data_administrative_3["long_name"]);
          }
          if (data_administrative_2 !== undefined) {
            data_arr.push(data_administrative_2["long_name"]);
          }
          if (data_administrative_1 !== undefined) {
            data_arr.push(data_administrative_1["long_name"]);
          }
          if (data_country !== undefined) {
            data_arr.push(data_country["long_name"]);
          }

          data_arr.forEach(function(data) {
            var node = document.createElement("LI");
            var textnode = document.createTextNode(data);
            node.appendChild(textnode);
            document.getElementById("data_area").appendChild(node);
          });
        } else {
          window.alert('No data!');
        }
      } else {
        window.alert('Geocoder failed: ' + status);
      }
    });
  }
</script>

<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>