如何将Google Places API与搜索按钮配合使用?

时间:2013-12-10 10:06:03

标签: javascript google-places-api

我在我的项目中使用Google Places API。当我在文本框中输入一些输入并在键盘上点击“输入”时它工作正常。它显示了结果。

但是,我想在文本框旁边放置搜索按钮,当我按下搜索按钮时,应显示结果。

这是我的初始化功能。

function initialize() {
  ...
  google.maps.event.addListener(searchBox, 'places_changed', function() {

    // When I hit Enter button the execution directly comes here.
    // I don't know how to work with onClick function for this purpose.

    var places = searchBox.getPlaces();
    for (var i = 0, marker; marker = markers[i]; i++) {
      marker.setMap(null);
    }
  }
}

3 个答案:

答案 0 :(得分:3)

我最近实施了类似的东西。我需要使用两种不同的功能;一个用于调用places_changed(已经有地理位置数据),另一个用于触发按钮事件时需要手动管理对Google的地理定位调用。您的代码可能如下所示:

var searchBox, map, geocoder;

function processPlacesSearch() {
  var places = searchBox.getPlaces();
  if (places.length) {
    location = places[0].geometry.location;
    var origin = new google.maps.LatLng(location.lat(), location.lng());
    // plot origin
  }
}

function processButtonSearch(location) {
  geocoder = new google.maps.Geocoder();
  geocoder.geocode(location, function (data) {
    var lat = data[0].geometry.location.lat();
    var lng = data[0].geometry.location.lng();
    var origin = new google.maps.LatLng(lat, lng);
    // plot origin
  });
}

function initialize() {
  map = new google.maps.Map(document.getElementById('map'), options);
  searchBox = new google.maps.places.SearchBox(document.getElementById('searchbox'));
  google.maps.event.addListener(searchBox, 'places_changed', processPlacesSearch);
}

var button = document.getElementById('searchbutton');
var searchbox = document.getElementById('searchbox');

button.onclick = function () {
  var location = searchbox.value;
  processButtonSearch(location);
}

答案 1 :(得分:2)

我不认为这些答案仍然存在,但这份文件对我来说很有帮助。

https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

当按钮通过gecoder和地图,然后处理搜索框值。

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 8,
      center: {lat: -34.397, lng: 150.644}
    });
    var geocoder = new google.maps.Geocoder();

    document.getElementById('submit').addEventListener('click', function() {
      geocodeAddress(geocoder, map);
    });
  }

  function geocodeAddress(geocoder, resultsMap) {
    var address = document.getElementById('address').value;
    geocoder.geocode({'address': address}, function(results, status) {
      if (status === 'OK') {
        resultsMap.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
          map: resultsMap,
          position: results[0].geometry.location
        });
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

答案 2 :(得分:0)

以下示例演示如何:

  • 在搜索框旁边放置一个搜索按钮

  • 单击按钮后显示结果(而不是在从Place Autocomplete中选择项目后显示的标准行为)



function initAutocomplete() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -33.8688, lng: 151.2195 },
        zoom: 13,
        mapTypeId: 'roadmap'
    });

    // Create the search box and link it to the UI element.
    var searchInput = document.getElementById('pac-input');
    var searchBtn = document.getElementById('search-button');
    var searchBox = new google.maps.places.SearchBox(searchInput);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchInput);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBtn);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function () {
        searchBox.setBounds(map.getBounds());
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function () {
        //displaySearchResults(map, searchBox, markers);
    });

    
    searchBtn.onclick = function () {
        displaySearchResults(map,searchBox,markers);
    }
}



function displaySearchResults(map, searchBox, markers) {
    var places = searchBox.getPlaces();

    if (places.length == 0) {
        return;
    }

    // Clear out the old markers.
    markers.forEach(function (marker) {
        marker.setMap(null);
    });
    markers = [];

    // For each place, get the icon, name and location.
    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)
        };

        // Create a marker for each place.
        markers.push(new google.maps.Marker({
            map: map,
            icon: icon,
            title: place.name,
            position: place.geometry.location
        }));

        if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
        } else {
            bounds.extend(place.geometry.location);
        }
    });
    map.fitBounds(bounds);
}

initAutocomplete();

html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
      .controls {
        margin-top: 10px;
        border: 1px solid transparent;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        height: 32px;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      }

      #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: 300px;
      }

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

      .pac-container {
        font-family: Roboto;
      }

      #type-selector {
        color: #fff;
        background-color: #4d90fe;
        padding: 5px 11px 0px 11px;
      }

      #type-selector label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
      #target {
        width: 345px;
      }


button[id="search-button"] {
    margin-left: -50px;
    margin-top: 10px;
    height: 32px;
    width: 50px;
    background: blue;
    color: white;
    border: 0;
    -webkit-appearance: none;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css" />
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<button id="search-button" class="icon"><i class="fa fa-search"></i></button>
<div id="map"></div>
    
&#13;
&#13;
&#13;