raghuveer999
raghuveer999

Reputation: 709

How to use Google Places API with a search button?

I am using Google Places API in my project. It is working fine when I give some input in a text box and hit "enter" on keyboard. It is showing results.

But, I want to place search button beside the textbox and when I press the search button, the results should be shown.

This is my initialze function.

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

Upvotes: 4

Views: 14382

Answers (3)

jsg
jsg

Reputation: 1264

I don't think these answers are still in date, but this documentation helped massively for me.

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

As the button passes through gecoder and the map, which then processes the search box value.

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

Upvotes: 3

Andy
Andy

Reputation: 63524

I implemented something similar recently. I needed to use two different functions; one for when places_changed is called (which already has the geolocation data) and one for when the button event is triggered which needs to manage the geolocation call to Google manually. You code might look something like this:

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

Upvotes: 3

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59338

The following example demonstrates how to:

  • place a search button next to the search box

  • display results once the button clicked (instead of standard behavior when it is displayed once the item is selected from 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>
    

Upvotes: 0

Related Questions