|
import {isEmpty, reduce} from 'lodash'; |
|
|
|
const parseRestrictions = (types, values, input) => ({ |
|
types, // address geocode |
|
componentRestrictions: values, |
|
input |
|
}); |
|
|
|
const searchBy = (country, city, address, input) => { |
|
let full_address = {}; |
|
let types; |
|
if (country) { |
|
types = ['(cities)']; |
|
full_address.country = country.toLowerCase(); |
|
} |
|
if (city) { |
|
types = ['address']; |
|
if (!isEmpty(input)) { |
|
input = city + ', ' + input; |
|
} |
|
} |
|
if (address) { |
|
types = ['geocode']; |
|
full_address.street_address = address; |
|
} |
|
return parseRestrictions(types, full_address, input) |
|
}; |
|
|
|
const createGoogleAutocompleteFilter = ac => (country, city, address, input) => { |
|
let options = searchBy(country, city, address, input); |
|
ac.setComponentRestrictions(options.componentRestrictions); |
|
ac.setTypes(options.types); |
|
}; |
|
|
|
const createGoogleAutocomplete = (element, callback) => { |
|
let autocomplete = new google.maps.places.Autocomplete(element); |
|
autocomplete.addListener('place_changed', function() { |
|
callback(this.getPlace().address_components); |
|
}); |
|
return autocomplete; |
|
}; |
|
|
|
const clearGoogleAutocomplete = (ac, element) => { |
|
ac.unbindAll(); |
|
google.maps.event.clearInstanceListeners(element); |
|
}; |
|
|
|
const createGoogleAutocompleteServiceFilter = (ac, cb) => (country, city, address, input) => { |
|
let options = searchBy(country, city, address, input); |
|
ac.getPlacePredictions(options, cb); |
|
}; |
|
|
|
const createGoogleAutocompleteService = (country, city, address, input) => new Promise((callback) => { |
|
let autocomplete = new google.maps.places.AutocompleteService(); |
|
const OK = google.maps.places.PlacesServiceStatus.OK; |
|
return createGoogleAutocompleteServiceFilter(autocomplete, function (predictions, status) { |
|
if (status !== OK) { |
|
return; |
|
} |
|
callback(predictions) |
|
})(country, city, address, input); |
|
}); |
|
|
|
const call = fn => (...args) => typeof google !== 'undefined' |
|
? fn(...args) |
|
: Promise.reject('Google API is not ready jet'); |
|
|
|
export const createAutocomplete = call(createGoogleAutocomplete); |
|
export const createAutocompleteFilter = call(createGoogleAutocompleteFilter); |
|
export const createAutocompleteService = call(createGoogleAutocompleteService); |
|
export const clearAutocomplete = call(clearGoogleAutocomplete); |