【问题标题】:Custom Search box for Google map谷歌地图的自定义搜索框
【发布时间】:2014-06-21 14:37:13
【问题描述】:

我正在使用 Google 地图 JavaScript 版本开发 Web 应用程序。我需要添加搜索框,如谷歌地图上的谷歌搜索框(如附图)。我需要搜索数据库中的自定义地点。

如果可以,怎么做?

【问题讨论】:

    标签: html css google-maps google-maps-api-3


    【解决方案1】:

    此示例使用 Google Place 自动完成功能向地图添加搜索框。人们可以输入地理搜索。搜索框将返回一个包含地点和预测搜索字词的选择列表。

    function initialize() {
    
      var markers = [];
      var map = new google.maps.Map(document.getElementById('map-canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    
    var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-33.8902, 151.1759),
      new google.maps.LatLng(-33.8474, 151.2631));
    map.fitBounds(defaultBounds);
    
    // Create the search box and link it to the UI element.
    var input = /** @type {HTMLInputElement} */(
      document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    
    var searchBox = new google.maps.places.SearchBox(
    /** @type {HTMLInputElement} */(input));
    
    // Listen for the event fired when the user selects an item from the
    // pick list. Retrieve the matching places for that item.
    google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();
    
    for (var i = 0, marker; marker = markers[i]; i++) {
      marker.setMap(null);
    }
    
    // For each place, get the icon, place name, and location.
    markers = [];
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
      var image = {
        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)
      };
    
      // Create a marker for each place.
      var marker = new google.maps.Marker({
        map: map,
        icon: image,
        title: place.name,
        position: place.geometry.location
      });
    
      markers.push(marker);
    
      bounds.extend(place.geometry.location);
    }
    
    map.fitBounds(bounds);
    });
    
    // Bias the SearchBox results towards places that are within the bounds of the
    // current map's viewport.
    google.maps.event.addListener(map, 'bounds_changed', function() {
    var bounds = map.getBounds();
    searchBox.setBounds(bounds);
    });
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    

    【讨论】:

    • 感谢您的回复。实际上我想从我的数据库而不是谷歌中获取搜索地点..那么如何从我的数据库中获取搜索结果?在此示例中,我无法从 Google 获取结果数据。
    • 如果您想从数据库中检索地点,您必须编写数据库连接代码。之后,您必须使用自动完成搜索框检索地点。
    猜你喜欢
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2014-01-22
    • 1970-01-01
    相关资源
    最近更新 更多