如何在谷歌地图中放置搜索框

时间:2015-08-21 22:28:42

标签: javascript google-maps

此搜索框不适用于搜索地点,我只想获得用户的输入。这个sample很好,除了我不需要自动完成功能。

或者你能告诉我如何使用css和javascript将搜索框放在谷歌地图上,如下所示: Looks like this :

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用Custom Control在地图上显示HTML <input>

proof of concept fiddle

代码段

var map;

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  // Create the DIV to hold the control and call the CenterControl() constructor
  // passing in this DIV.
  var centerControlDiv = document.createElement('div');
  var centerControl = new CenterControl(centerControlDiv, map);

  centerControlDiv.index = 1;
  centerControlDiv.style['padding-top'] = '20px';
  centerControlDiv.style['padding-left'] = '20px';
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(centerControlDiv);
}
google.maps.event.addDomListener(window, "load", initialize);
/**
 * The CenterControl adds a control to the map that recenters the map on Chicago.
 * This constructor takes the control DIV as an argument.
 * @constructor
 */
function CenterControl(controlDiv, map) {

  // Set CSS for the control border.
  var controlUI = document.createElement('div');
  controlUI.style.backgroundColor = '#fff';
  controlUI.style.border = '2px solid #fff';
  controlUI.style.borderRadius = '3px';
  controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
  controlUI.style.cursor = 'pointer';
  controlUI.style.marginBottom = '22px';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to recenter the map';
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior.
  var controlText = document.createElement('input');
  controlText.style.color = 'rgb(25,25,25)';
  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
  controlText.style.fontSize = '16px';
  controlText.style.lineHeight = '38px';
  controlText.style.paddingLeft = '5px';
  controlText.style.paddingRight = '5px';
  controlText.size = "50";
  controlText.value = 'Search Box';
  controlUI.appendChild(controlText);
}
html,
body,
#map {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>