• Stars
    star
    1,021
  • Rank 45,070 (Top 0.9 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A React autosuggest for the Google Maps Places API.

React Geosuggest Build Status

A React autosuggest for the Google Maps Places API. You can also define your own suggests as defaults. Works with Preact, too.

Demo

Live demo: ubilabs.github.io/react-geosuggest

Installation

As this component uses the Google Maps Places API to get suggests, you must include the Google Maps Places API in the <head> of your HTML:

<!DOCTYPE html>
  <html>
  <head>
    …
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&libraries=places"></script>
  </head>
  <body>
    …
  </body>
</html>

Visit the Google Developer Console to generate your API key. The API's that you have to enable in your Google API Manager Dashboard are Google Maps Geocoding API, Google Places API Web Service and Google Maps Javascript API.

The easiest way to use geosuggest is to install it from NPM and include it in your own React build process (using Webpack, Parcel, etc).

You can also use the standalone build by including dist/react-geosuggest.js in your page. If you use this, make sure you have already included React, and it is available as a global variable.

npm install react-geosuggest --save

Usage

The Geosuggest works out of the box by just including it. However, you can customize the behaviour with the properties noted below.

ES6:

import Geosuggest from 'react-geosuggest';

<Geosuggest />

ES5:

var Geosuggest = require('react-geosuggest').default;

<Geosuggest />

Properties

placeholder

Type: String Default: Search places

The input field will get this placeholder text.

initialValue

Type: String Default: ''

An initial value for the input, when you want to prefill the suggest.

id

Type: String Default: ''

Define an ID for the geosuggest. Needed when there are multiple instances on a page.

className

Type: String Default: ''

Add an additional class to the geosuggest container.

style

Type: Object Default: { 'input': {}, 'suggests': {}, 'suggestItem': {} }

Add an additional style to Geosuggest. This would support overriding/adding styles to the input suggestList and suggestItem.

inputClassName

Type: String Default: ''

Add an additional class to the input.

disabled

Type: Boolean Default: false

Defines whether the input is disabled.

location

Type: google.maps.LatLng Default: null

To get localized suggestions, define a location to bias the suggests.

radius

Type: Number Default: 0

The radius in meters defines the area around the location to use for biasing the suggests. It must be accompanied by a location parameter.

bounds

Type: LatLngBounds Default: null

The bounds to use for biasing the suggests. If this is set, location and radius are ignored.

country

Type: String or Array Default: null

Restricts predictions to the specified country (ISO 3166-1 Alpha-2 country code, case insensitive). E.g., us, br, au. You can provide a single one, or an array of up to 5 country code strings.

types

Type: Array Default: null

The types of predictions to be returned. Four types are supported: establishment for businesses, geocode for addresses, (regions) for administrative regions and (cities) for localities. If nothing is specified, all types are returned. Consult the Google Docs for up to date types.

fixtures

Type: Array Default: []

An array with fixtures (defaults). Each fixture has to be an object with a label key in it. Optionally provide a location, but the Geosuggest will geocode the label if no location is provided.

You can also add a className key to a fixture. This class will be applied to the fixture item.

maxFixtures

Type: Number Default: 10

Maximum number of fixtures to render.

placeDetailFields

Type: Array Default: null

By default Google returns all fields when getting place details which can impact billing. You can optionally pass an array of fields to include in place results to limit what is returned and potentially reduce billing impact. geometry will always be added as we depend on the location for the suggest selection.

googleMaps

Type: Object Default: google.maps

In case you want to provide your own Google Maps object, pass it in as googleMaps. The default is the global google maps object.

ignoreTab

Type: Boolean Default: false

When the tab key is pressed, the onSelect handler is invoked. Set to true to not invoke onSelect on tab press.

ignoreEnter

Type: Boolean Default: false

When the enter key is pressed, the onSelect handler is invoked. Set to true to not invoke onSelect on enter press.

queryDelay

Type: Number Default: 250

Sets the delay in milliseconds after typing before a request will be sent to find suggestions. Specify 0 if you wish to fetch suggestions after every keystroke.

minLength

Type: Number Default: 1

Sets a minimum length of characters before a request will be sent to find suggestions.

highlightMatch

Type: Boolean Default: true

Highlights matched text.

onFocus

Type: Function Default: function() {}

Gets triggered when the input field receives focus.

onBlur

Type: Function Default: function(value) {}

Gets triggered when input field loses focus.

onChange

Type: Function Default: function(value) {}

Gets triggered when input field changes the value.

onKeyDown

Type: Function Default: function(event) {}

Gets triggered when input field has a key pressed down. This event is triggered before onKeyPress.

onKeyPress

Type: Function Default: function(event) {}

Gets triggered when input field gets key press.

onSuggestSelect

Type: Function Default: function(suggest) {}

Gets triggered when a suggest got selected. Only parameter is an object with data of the selected suggest. This data is available:

  • label – Type String – The label name
  • placeId – Type String – If it is a preset, equals the label. Else it is the Google Maps placeID
  • location – Type Object – The location containing lat and lng
  • gmaps – Type Object – Optional! The complete response when there was a Google Maps geocode necessary (e.g. no location provided for presets). Check the Google Maps Reference for more information on it’s structure.

onUpdateSuggests

Type: Function Default: function(suggests, activeSuggest) {}

Gets triggered when the suggest list changes. Arguments include the suggest list and the current activeSuggest. Useful if you want to render the list of suggests outside of react-geosuggest.

onActivateSuggest

Type: Function Default: function(suggest) {}

Gets triggered when a suggest is activated in the list. Only parameter is an object with data of the selected suggest. This data is available:

  • label – Type String – The label name
  • placeId – Type String – If it is a preset, equals the label. Else it is the Google Maps placeID

onSuggestNoResults

Type: Function Default: function(userInput) {}

Gets triggered when there are no suggest results found

getSuggestLabel

Type: Function Default: function(suggest) { return suggest.description; }

Used to generate a custom label for a suggest. Only parameter is a suggest (google.maps.places.AutocompletePrediction). Check the Google Maps Reference for more information on it’s structure.

renderSuggestItem

Type: Function Default: null

Used to customize the inner html of SuggestItem and allows for controlling what properties of the suggest object you want to render. Also a convenient way to add additional styling to different rendered elements within SuggestItem. The function is passed both the suggestion and the user input.

skipSuggest

Type: Function Default: function(suggest) {}

If the function returns true then the suggest will not be included in the displayed results. Only parameter is an object with data of the selected suggest. (See above)

autoActivateFirstSuggest

Type: Boolean Default: false

Automatically activate the first suggestion as you type. If false, the exact term(s) in the input will be used when searching and may return a result not in the list of suggestions.

label

Type: String Default: null

If the label and a id prop (see "Others") were supplied, a <label> tag with the passed label text will be rendered. The <label> element's for attribute will correctly point to the id of the <input> element.

suggestsClassName

Type: String Default: ''

Add an additional class to suggest list.

suggestsHiddenClassName

Type: String Default: null

Additional className to toggle as the list of suggestions changes visibility.

suggestItemClassName

Type: String Default: ''

Add an additional class to suggest item.

suggestItemActiveClassName

Type: String, Default: null

Additional className to add when a suggestion item is active.

autoComplete

Type: String, Default: nope

Autocomplete input attribute.

inputType

Type: String, Default: text

The value for the type attribute on the html input element. Can be either text or search.

Others

All allowed attributes for input[type="text"] All DOM clipboard events. All DOM mouse events except for drag & drop. All data attributes.

Exposed component functions

These functions are accessible by setting "ref" on the component (see example below)

focus()

Call focus to focus on the element. The suggest list will be expanded with the current suggestions.

blur()

Call blur to blur (unfocus) the element. The suggest list will be closed.

update(value)

It is possible to update the value of the input contained within the GeoSuggest component by calling the update function with a new desired value of the type String.

clear()

It is also possible to clear the value of the input contained within the GeoSuggest component by calling the clear function.

selectSuggest()

Same effect as hitting enter (will geocode the text inside of the input).

Example

import React, {useRef} from 'react';
import ReactDOM from 'react-dom';
import Geosuggest from 'react-geosuggest';

const App = () => {
  const geosuggestEl = useRef(null);

  const fixtures = [
    {label: 'New York', location: {lat: 40.7033127, lng: -73.979681}},
    {label: 'Rio', location: {lat: -22.066452, lng: -42.9232368}},
    {label: 'Tokyo', location: {lat: 35.673343, lng: 139.710388}}
  ];

  /**
   * When a suggest got selected
   */
  const onSuggestSelect = (suggest) => console.log(suggest);

  return (
    <div>
      <Geosuggest
        ref={geosuggestEl}
        placeholder="Start typing!"
        initialValue="Hamburg"
        fixtures={fixtures}
        onSuggestSelect={onSuggestSelect}
        location={new google.maps.LatLng(53.558572, 9.9278215)}
        radius="20" />

      {* Buttons to trigger exposed component functions *}
      <button onClick={()=>geosuggestEl.current.focus()}>Focus</button>
      <button onClick={()=>geosuggestEl.current.update('New Zealand')}>Update</button>
      <button onClick={()=>geosuggestEl.current.clear()}>Clear</button>
      <button onClick={()=>geosuggestEl.current.selectSuggest()}>Search</button>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('app'));

Styling

This component uses BEM for namespacing the CSS classes. So styling should be easy and without conflicts. See the geosuggest.css for an example styling.

Note:

The geosuggest__suggests--hidden class is added to hide the suggestion list. You should copy the style below into your CSS file.

.geosuggest__suggests--hidden {
  max-height: 0;
  overflow: hidden;
  border-width: 0;
}

The above class is added whenever the suggestion list needs to be hidden. This occurs when the user selects an item from the list or when the user triggers the blur event on the input.

Similarly, you need to have the class geosuggest__item--active similar to this:

.geosuggest__item--active {
  background: #267dc0;
  color: #fff;
}

to see what item is selected, f.ex. when using the arrow keys to navigate the suggestion list.

Contributing

Issues and pull requests are welcome! Please read the guidelines in CONTRIBUTING.md before starting to work on a PR.

License

See LICENSE.md

More Repositories

1

geocomplete

jQuery Geocoding and Places Autocomplete Plugin
JavaScript
1,227
star
2

kd-tree-javascript

JavaScript k-d Tree Implementation
JavaScript
607
star
3

axidraw

Use JavaScript to draw on any flat surface with the friendly AxiDraw robot
JavaScript
161
star
4

google-maps-api-threejs-layer

Google Maps API layer that uses Three.js to for super fast animation
JavaScript
159
star
5

google-maps-react-hooks

The JavaScript library to easily implement a Google Maps map into your react application. It comes with a collection of React hooks to access the map instance or different Maps JavaScript Services.
TypeScript
73
star
6

threejs-overlay-view

A wrapper for the Google Maps WebglOverlayView that takes care of the integration between three.js and the Google Maps JavaScript API. It lets you create a Google Map overlays directly with three.js.
TypeScript
55
star
7

google.maps.polyline.edit

Enables Google Maps API V3 Polyline Editing
JavaScript
33
star
8

mobile-range-slider

A lightweight JavaScript range slider that works on mobile devices such as iOS or Android.
JavaScript
20
star
9

google-maps-api-svg-overlay

SVG Overlay for the Google Maps JavaScript API v3
JavaScript
16
star
10

google-maps-deckgl-overlay

An example for using a Google Map with Deck.gl
JavaScript
13
star
11

geolocation-remote

Geolocation Remote - Control the Location of Your Mobile Device
JavaScript
11
star
12

node-geobatch

Batch geocode addresses from multiple sources.
JavaScript
10
star
13

esa-climate-from-space

Climate from Space application for ESA's CCI+ program.
TypeScript
9
star
14

project-template

The project creation tooling used at Ubilabs
JavaScript
9
star
15

node-stagger

Execute a stack with a given "request-per-seconds" and "max" rate.
JavaScript
9
star
16

refinery-custom-page-parts

Custom page parts for refinery
Ruby
8
star
17

soccer-debs-challenge

The ACM DEBS 2013 Grand Challenge
JavaScript
8
star
18

webpack-node-modules-list

Exports all used node modules of a webpack bundle to a file.
JavaScript
8
star
19

node-batch-geocoder

Node.js Batch Geocoder for the Google Maps API
JavaScript
7
star
20

node-image-saver

Saves an Image Data URI Back to the File System
JavaScript
7
star
21

node-parallel-transform-stream

A NodeJS transform stream which runs transformations in parallel and preserves input order.
JavaScript
6
star
22

sunzi-recipes

Our server provisioning recipes for sunzi.
Shell
6
star
23

flickr_geocoding_bookmarklet

A Bookmarklet for Better Geocoding within Flickr using Google Maps
JavaScript
6
star
24

grunt-gcloud

A wrapper for the google-gcloud node module.
JavaScript
5
star
25

icons_generator

Multiple Icons Generator using Ruby and ImageMagick
Ruby
5
star
26

touchstates

jQuery Touch State Plugin
JavaScript
4
star
27

kirby-object-storage-stream-wrappers

Prototype to run a Kirby CMS instance with data on Object Storage (GCS)
4
star
28

google-map-bounds-limit

Limits zoom and panning of a google map
JavaScript
4
star
29

cookbooks

Our Fancy Chef Cookbooks
Ruby
3
star
30

fastbillr

Ruby Api wrapper for the fastbill.com API
Ruby
3
star
31

stackenblochen

A grid system for rectanglers.
CSS
2
star
32

jquery-touchevents

jQuery Plugin to Proxy Touch Events
JavaScript
2
star
33

esa-webgl-globe

TypeScript
2
star
34

google-maps-visualrefresh

Comparing the new and old Google Maps styles.
1
star
35

node-google-maps-api-stream

A streaming, rate-limited, and caching interface to Google Maps APIs.
JavaScript
1
star
36

image-performance

Test Image Rendering Performance on Various Browsers
1
star
37

nagios-plugins

A collection of custom Nagios plugins that we use @ubilabs.
Shell
1
star
38

fusion_wiki

1
star
39

storycamp

Basecamp Story Card Printer for Google Chrome
JavaScript
1
star
40

retrobox

Ruby
1
star
41

drone_elixir_example

Example to show some examples on drone.io. This one is for elixir
Elixir
1
star
42

ubilabs.github.com

1
star
43

basic_server_stack

Ruby
1
star
44

gdd

1
star
45

node-api-stream

Create streaming, rate-limited APIs with ease.
JavaScript
1
star
46

binary-view.js

Binary schemes for JavaScript. Let's you define (write and load) binary formats
JavaScript
1
star
47

babylonian

A Mixed Languages Map Type
1
star
48

template

HTML, CSS and JavaScript Templates
JavaScript
1
star