Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

javascript - Google地图将位置设置为适合屏幕的不同边界(Google maps fit location to screen with different bounds)

Firstly, I have been checking all over the web but I couldnt find an answer.(首先,我已经检查了整个网络,但是找不到答案。)

I combined autocomplete with goole maps and if a user wants, he/she can move the marker as well and I get address from it.(我将自动完成功能与goole映射结合在一起,如果用户需要,他/她也可以移动标记,然后从中获取地址。)

You can find the code below.(您可以在下面找到代码。)

When a user searches for instance Nice, France, is it possible to fit Nice from eg borders to my map?(当用户搜索法国尼斯时,是否可以将尼斯从例如边界放置到我的地图上?)

Maybe I have to change the zoom dynamically or I need to set new viewport, I am not sure.(不确定我可能必须动态更改缩放比例,或者需要设置新的视口。) So far what I found is, I can give a distance and create a circle to fit that circle to the viewport.(到目前为止,我发现可以给出一个距离并创建一个圆,以使该圆适合视口。) But circle's radius is set, so it can fit to Nice but can not fit to Miami.(但是设置了圆的半径,因此它可以适合尼斯,但不能适合迈阿密。)

Hope I could explain what I mean.(希望我能解释我的意思。)

Thank you in advance.(先感谢您。)
<!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> 
  ask by Shalafister's translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Autocomplete service returns the geometry of the location selected, zoom the map to show those bounds (in the fiddle/snippet I added a rectangle to show the bounds returned, if you don't want that displayed, remove it):(Autocomplete服务会返回所选位置的几何形状,缩放地图以显示这些边界(在小提琴/摘录中,我添加了一个矩形以显示返回的边界,如果不想显示该边界,则将其删除):)

  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> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...