将Google地图圆半径设置为输入框值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将Google地图圆半径设置为输入框值相关的知识,希望对你有一定的参考价值。

我正在尝试在谷歌地图中创建一个工具,该工具显示一个圆圈中的标记数量(由php编码连接加载到mysql数据库),该圆圈使用搜索框放置。这很好,感谢几个星期前我在这个网站上收到的帮助。从那时起,我花了几天时间(开启和关闭)尝试将圆的半径更改为输入到已放置在地图上的用户输入框中的值。

输入框的on click函数抛出错误,表示函数未定义。我相信这是因为名为'updateRadius()'的函数中存在错误,它无法找到我在代码中先前声明的circle变量。

我希望有人可以就此提出建议。谢谢。请参阅以下代码:

<!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Using MySQL and PHP with Google Maps</title>

<style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 75%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      /*Styles for Search Box*/
      #description {
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
      }

      #infowindow-content .title {
        font-weight: bold;
      }

      #infowindow-content {
        display: none;
      }

      #map #infowindow-content {
        display: inline;
      }

      .pac-card {
        margin: 10px 10px 0 0;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        background-color: #fff;
        font-family: Roboto;
      }

      #pac-container {
        padding-bottom: 12px;
        margin-right: 12px;
      }

      .pac-controls {
        display: inline-block;
        padding: 5px 11px;
      }

      .pac-controls label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 400px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      #title {
        color: #fff;
        background-color: #4d90fe;
        font-size: 25px;
        font-weight: 500;
        padding: 6px 12px;
      }
      #target {
        width: 345px;
      }

/*Add Styles Radius input box here*/
      .map-control {
        background-color: #fff;
        border: 1px solid #ccc;
        box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4);
        font-family: 'Roboto','sans-serif';
        margin: 10px;
        /* Hide the control initially, to prevent it from appearing
           before the map loads. */
        display: none;
      }
      /* Display the control once it is inside the map. */
      #map .map-control { display: block; }

      .selector-control {
        font-size: 14px;
        line-height: 30px;
        padding-left: 5px;
        padding-right: 5px;
      }

    </style>

  </head>

  <body>


    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map"></div>
    <input id="rad" placeholder="Radius" value="200"></input>
    <input id="radius" type="button" value="Click" onclick="updateRadius()"/>

    <script>

var image = 'http://maps.google.com/mapfiles/kml/pal4/icon57.png';

      /*var customLabel = {
        TE: {
          label: 'T'      }
      };*/

        function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(40.784032, -73.964436),
          zoom: 12,
          mapTypeControl: false

        });
        var infoWindow = new google.maps.InfoWindow;

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

                      // Add a style-selector control to the map.
        //var styleControl = document.getElementById('style-selector-control');
        //map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(styleControl);

        var inputBox = document.getElementById('rad');
        map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(inputBox)
        map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(radius)


  //var searchBox = new google.maps.places.SearchBox(input);
  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.

  var circle = new google.maps.Circle ({
        map: map,
        //center: new google.maps.LatLng (40.758789, -73.978717),
        radius: 200,
        strokeColor: "#00ff00",
        fillcolor: "red",
        editable: true

  });


  google.maps.event.addListener(searchBox, 'places_changed', function() {
    var place = searchBox.getPlaces()[0];

    if (!place.geometry) return;
    // If the place has a geometry, then present it on a map.
    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
      circle.setCenter(place.geometry.location);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);
    }
  });

           function updateRadius(){
        var radi = document.getElementById('rad').value;
        circle.setRadius(parseFloat(radi));
      }




          // Change this depending on the name of your PHP or XML file
          downloadUrl('googleMap.php', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
              var id = markerElem.getAttribute('id');
              var name = markerElem.getAttribute('name');
              var address = markerElem.getAttribute('address');
              var type = markerElem.getAttribute('type');
              var point = new google.maps.LatLng(
                  parseFloat(markerElem.getAttribute('lat')),
                  parseFloat(markerElem.getAttribute('lng')));

              var infowincontent = document.createElement('div');
              var strong = document.createElement('strong');
              strong.textContent = name
              infowincontent.appendChild(strong);
              infowincontent.appendChild(document.createElement('br'));

              var text = document.createElement('text');
              text.textContent = address
              infowincontent.appendChild(text);
              /*var icon = customLabel[type] || {};*/
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                /*label: icon.label,*/
                icon: image
              });
              marker.addListener('click', function() {
                infoWindow.setContent(infowincontent);
                infoWindow.open(map, marker);
              });
            });
          });
        }


      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
          }
        };

        request.open('GET', url, true);
        request.send(null);
      }

      function doNothing() {}

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"
         async defer></script>
  </body>
</html>
答案

此问题是由于函数的嵌套造成的。基本上你有这个:

<body>
    <input id="radius" onclick="updateRadius()"/>
    <script>
    function initAutocomplete() {
        var circle = new google.maps.Circle ({...});

        updateRadius() {...}
    }
</body>

在这种情况下,updateRadius需要访问它所拥有的circle,因为它们都在相同的范围内(initAutocomplete的范围。问题是因为它们是在initAutocomplete中定义的,所以它们在该函数之外是不可见的。你的输入尝试调用updateRadius,但它无法访问initAutocomplete的范围,这就是你得到错误的原因。解决这个问题的一个简单方法就是将updateRadius添加到window(基本上使它成为一个全局变量)。这不是一个大型站点的理想解决方案,但可能解决您的问题。您可以通过更改此设置:

function updateRadius() {
    ...
}

进入这个:

window.updateRadius = function() {
    ...
}

希望有所帮助,如果您需要我澄清一些事情,请告诉我。

以上是关于将Google地图圆半径设置为输入框值的主要内容,如果未能解决你的问题,请参考以下文章

如何为谷歌地图信息窗口设置边界半径

# 如何圈出某点周边半径2公里的圆(用百度地图)?

如何在所有缩放级别中创建具有相同半径的谷歌地图 v3 圆?

在地图上以米为单位绘制圆

相对于缩放级别缩放 MKMapView 注释

求用python输入圆的半径,计算圆的周长和面积,结果保留2位小数的代码