html - 谷歌地图的自定义搜索框

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

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

enter image description here

如果可以,怎么做?

最佳答案

此示例使用 Google Place Autocomplete 功能向 map 添加搜索框。人们可以输入地理搜索。搜索框将返回一个选择列表,其中包含地点和预测搜索词的组合。

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);

关于html - 谷歌地图的自定义搜索框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23470005/

相关文章:

android - Android Maps Api 有配额吗?

javascript - 带有页眉和页脚的双动画模态

jquery - 将窗口高度设置为 div 时,为什么要额外添加 10000?

html - 使用包装器将列表中的 4 张图像与页面的中心对齐

javascript - map 绘制显示错误 - TypeError : k[bd].maps.Load 不是函数

javascript - 谷歌地图 API v3 : Can I setZoom after fitBounds?

html - 随着内容扩展 div 宽度

javascript - 如何保存/读取 HTML 中随机打开页面的 cookie 信息?

javascript - 使用 Javascript 计算某个字符串在页面上出现的次数

html - 如何裁剪图像边缘