JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.css">
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCa0ALxq4q2PDyFh0iWG1rYz4D5zmgl2K8&libraries=places"></script>
<h1>
<a href="https://github.com/algolia/instantsearch.js/">instantsearch.js</a> google map example
<small>searching for apartments</small>
</h1>
<div>
<label>Algolia search (full text):
<input id="searchBox" />
</label>
</div>
<div>
<label>Refine with a place: (google autocomplete)
<input id="places" />
</label>
</div>
<h2>
Available apartments
</h2>
<div id="hits"></div>
<h2>
Map display (google map)
</h2>
<div id="map">
</div>
CSS
em {
color: #888;
font-style: normal
}
#map {
width: 300px;
height: 300px;
}
JavaScript
var apts = instantsearch({
appId: 'latency',
apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
indexName: 'airbnb',
});
var aptsHits = instantsearch.widgets.hits({
container: document.querySelector('#hits'),
hitsPerPage: 3,
templates: {
item: '{{address}}, bedrooms: {{bedrooms}}, price: {{price}}'
}
});
var searchBox = instantsearch.widgets.searchBox({
container: document.querySelector('#searchBox'),
wrapInput: false
});
var customMapWidget = {
_autocompleteContainer: document.querySelector('#places'),
_mapContainer: document.querySelector('#map'),
_hitToMarker: function(hit) {
return new google.maps.Marker({
position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng},
map: this._map,
title: hit.name
});
},
_handlePlaceChange: function(place) {
// https://developers.google.com/maps/documentation/javascript/reference#Autocomplete
var place = this._autocomplete.getPlace();
if (place.geometry === undefined) {
// user did not select any place, see https://developers.google.com/maps/documentation/javascript/reference#Autocomplete
// events paragraph
if (place.name === '') {
// input was cleared
this._helper
.setQueryParameter('aroundLatLng')
.search();
}
return;
}
// see https://developers.google.com/maps/documentation/javascript/reference#PlaceResult
var latlng = place.geometry.location.toUrlValue();
// https://www.algolia.com/doc/guides/geo-search/geo-search-overview/#filter-and-sort-around-a-location
this._helper
.setQueryParameter('aroundLatLng', latlng)
.search();
},
init: function(params) {
this._helper = params.helper;
this._autocomplete = new google.maps.places.Autocomplete(this._autocompleteContainer);
this._autocomplete.addListener('place_changed', this._handlePlaceChange.bind(this));
this._map = new google.maps.Map(this._mapContainer, {zoom: 1, center: new...