仅将谷歌地图限制设置为我的城市

时间:2016-01-18 13:15:17

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

在我的网站上(见下面的截图)如果我输入区域名称,它会显示带有区域的全局地图。但我希望它只适用于我的纬度经度。例如。如果我开始输入它应该只显示我的城市区域。我现在的城市是孟买。如何更改脚本以执行此类操作。我的网站链接是www.quista.in,您想要测试它。

JS。

   <script type="text/javascript">
        var source, destination;
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        google.maps.event.addDomListener(window, 'load', function () {
            new google.maps.places.SearchBox(document.getElementById('txtSource'));
            new google.maps.places.SearchBox(document.getElementById('txtDestination'));
            directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
        });

        function GetRoute() {
            debugger;
            var mumbai = new google.maps.LatLng(18.9750, 72.8258);
            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(28.30, 76.40),
                mapTypeControl: false,
                panControl: false,
                zoomControl: true,
                streetViewControl: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById('dvPanel'));

            //*********DIRECTIONS AND ROUTE**********************//
            source = document.getElementById("txtSource").value;
            destination = document.getElementById("txtDestination").value;

            var request = {
                origin: source,
                destination: destination,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });

            //*********DISTANCE AND DURATION**********************//
            var service = new google.maps.DistanceMatrixService();
            service.getDistanceMatrix({
                origins: [source],
                destinations: [destination],
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            }, function (response, status) {
                if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                    var distance = response.rows[0].elements[0].distance.text;
                    var duration = (response.rows[0].elements[0].duration.value / 60).toFixed(0);
                    var dvDuration = document.getElementById("dvDuration");
                    dvDuration.innerHTML = duration + 'minutes';
                    var dvDistance = document.getElementById("dvDistance");
                    var dvDuration = document.getElementById("dvDuration");
                    dvDistance.innerHTML = "";
                    dvDistance.value = parseFloat(distance);
                    dvDuration.innerHTML = duration;
                    dvDuration.value = (duration);
                } else {
                    alert("Unable to find the distance via road.");
                }
            });
        }
    </script>

enter image description here

1 个答案:

答案 0 :(得分:0)

要限制搜索到您所在的区域,您可以使用componentRestrictions选项。

  

&#34; Google开发者网站:使用componentRestrictions选项进行限制   自动完成对特定国家/地区的搜索。&#34;

// Set the country restriction based on user input.
// Also center and zoom the map on the given country.
function setAutocompleteCountry() {
  var country = document.getElementById('country').value;
  if (country == 'all') {
    autocomplete.setComponentRestrictions([]);
    map.setCenter({lat: 15, lng: 0});
    map.setZoom(2);
  } else {
    autocomplete.setComponentRestrictions({'country': country});
    map.setCenter(countries[country].center);
    map.setZoom(countries[country].zoom);
  }
  clearResults();
  clearMarkers();
}

您可以在此处了解详情:https://developers.google.com/maps/documentation/javascript/places-autocomplete

<强>更新

我创建了一个限制区域城市的片段(印度为你)。我已使用您的文字字段名称id="txtSource"

重命名文本字段

var countryRestrict = {'country': 'in'};此限制结果仅适用于印度的城市。您可以将其与您想要限制城市的其他国家/地区进行更改。

通过以下脚本替换GetRoute()函数。没有插入所需的功能。

<强>段

&#13;
&#13;
<div id="locationField">
    <input id="txtSource" placeholder="From Area" type="text" />
</div>

<script>
  var autocomplete;
  var countryRestrict = {'country': 'in'};
  function initMap() {
    autocomplete = new google.maps.places.Autocomplete(
   (
          document.getElementById('txtSource')), {
          types: ['(cities)'],
          componentRestrictions: countryRestrict
        });
  }
</script>

<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=places&callback=initMap" async defer></script>
&#13;
&#13;
&#13;

如果您只想要3个城市,则必须创建自己的select下拉菜单。例如:

<select id="city">
    <option value="pune">Pune</option>
    <option value="mumbai">Mumbai</option>
    ...
</select>