首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何将GoogleMap搜索框添加到我的地图?

要将GoogleMap搜索框添加到自己的地图,可以按照以下步骤进行操作:

  1. 首先,确保你已经有一个Google账号,并登录到Google开发者控制台(https://console.developers.google.com)。
  2. 在Google开发者控制台中,创建一个新的项目,并启用Maps JavaScript API。
  3. 在API库中,启用Places API。
  4. 在凭据页面中,创建一个API密钥。确保将此密钥限制为只能在你的网站上使用。
  5. 在你的网站的HTML文件中,添加以下代码片段:
代码语言:txt
复制
<!DOCTYPE html>
<html>
<head>
  <title>添加GoogleMap搜索框</title>
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
</head>
<body>
  <div id="map"></div>
  <input id="search" type="text" placeholder="搜索地点">
  <script>
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
      });
      
      var searchBox = new google.maps.places.SearchBox(document.getElementById('search'));
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(document.getElementById('search'));
      
      map.addListener('bounds_changed', function() {
        searchBox.setBounds(map.getBounds());
      });
      
      var markers = [];
      searchBox.addListener('places_changed', function() {
        var places = searchBox.getPlaces();
        
        if (places.length == 0) {
          return;
        }
        
        markers.forEach(function(marker) {
          marker.setMap(null);
        });
        markers = [];
        
        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)
          };
          
          markers.push(new google.maps.Marker({
            map: map,
            icon: icon,
            title: place.name,
            position: place.geometry.location
          }));
          
          if (place.geometry.viewport) {
            bounds.union(place.geometry.viewport);
          } else {
            bounds.extend(place.geometry.location);
          }
        });
        map.fitBounds(bounds);
      });
    }
  </script>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"></script>
</body>
</html>

请将上述代码中的YOUR_API_KEY替换为你在步骤4中创建的API密钥。

  1. 保存并运行你的网页,你将看到一个包含GoogleMap和搜索框的地图。你可以在搜索框中输入地点名称,地图将会定位到该地点,并在地图上显示相应的标记。

这样,你就成功地将GoogleMap搜索框添加到你的地图中了。

腾讯云相关产品和产品介绍链接地址:

  • 腾讯云地图服务:https://cloud.tencent.com/product/tianditu
  • 腾讯云位置服务:https://cloud.tencent.com/product/lbs
  • 腾讯云地理围栏:https://cloud.tencent.com/product/gis
  • 腾讯云地理信息系统:https://cloud.tencent.com/product/gis
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券