Giter Club home page Giter Club logo

geocomplete's Introduction

$.geocomplete() - Version 1.7.0

jQuery Geocoding and Places Autocomplete Plugin

An advanced jQuery plugin that wraps the Google Maps API's Geocoding and Places Autocomplete services. You simply provide an input that lets you search for locations with a nice autocomplete dropdown. Optionally add a container to show an interactive map and a form that will be populated with the address details.

View the annotated source.

⚠️ NOT MAINTAINED

Please note: This project is not maintained anymore. We do not use jQuery in production and switched to React about two years ago. Feel free to discuss issues here but please do not expect new features or changes in the default behavior.

For a new and way more flexible solution, see our React Geosuggest plugin.

If you would like to take over the project, please let us know! There are many people out there who would be happy to have new supporters.

Basic Usage

To convert an input into an autocomplete field, simply call the Geocomplete plugin:

$("input").geocomplete();  // Option 1: Call on element.
$.fn.geocomplete("input"); // Option 2: Pass element as argument.

Examples

Here is a list of basic uses:

  • Simple - Single input with an event logger.
  • Map - Adding a map.
  • Location - Adding a default location.
  • Form - Populate form fields.
  • Attribute - Using custom attributes to populate data.
  • Multiple results - Handling multiple results from the geocoder.
  • Draggable - A draggable marker to redefine the position.
  • Styled - A styled map example.

Requirements

Make sure you include the Google Maps API with the Places Library before loading this plugin as described here.

<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
<script src="jquery.geocomplete.js"></script>

If you use the plugin without showing a map you must display the "powered by Google" logo under the text field.

Trigger Request

To trigger a geocoding request from outside (eg. when hitting the "find" button), simply trigger the "geocode" event on the element.

$("input").geocomplete();

// Trigger geocoding request.
$("button.find").click(function(){
  $("input").trigger("geocode");
});

Adding a Map Preview

To link the geocode results with an interactive map, you can pass map as an option to the plugin.

$("#my_input").geocomplete({
  map: "#my_map"
});

The map option might be a selector, a jQuery object or a DOM element.

Populate Form Data

You can pass details as an option to specify a container that will be populated when a geocoding request was successful.

By default the plugin analyses the name attribute of the containers child nodes and replaces the content. You can override the detailsAttribute to use another attribute such as data-geo.

If the element is an input, the value will be replaced otherwise the plugin overrides the current text.

If you have multiple geocomplete fields on a page, use detailsScope option scope your 'details' container.

Note: Some address components such as "country" return an additional short_name. You can access them by simply adding _short at the end of the type.

Simple Example:

<form>
  Latitude:   <input name="lat" type="text" value="">
  Longitude:  <input name="lng" type="text" value="">
  Address:    <input name="formatted_address" type="text" value="">
</form>
$("input").geocomplete({ details: "form" });

Advanced Example:

<div class="details">
  Latitude:     <span data-geo="lat" />
  Longitude:    <span data-geo="lng" />
  Address:      <span data-geo="formatted_address" />
  Country Code: <span data-geo="country_short" />
</div>
$("input").geocomplete({
  details: ".details",
  detailsAttribute: "data-geo"
});

List of Options

The following options might be passed to the plugin call. If you omit them, they fall back to the default.

Example:

$("#my_input").geocomplete({
  map: "#my_map",
  mapOptions: {
    zoom: 10
  },
  markerOptions: {
    draggable: true
  },
  details: "#my_form"
});
  • map - Might be a selector, a jQuery object or a DOM element. Default is false which shows no map.
  • details - The container that should be populated with data. Defaults to false which ignores the setting.
  • 'detailsScope' - Allows you to scope the 'details' container and have multiple geocomplete fields on one page. Must be a parent of the input. Default is 'null'
  • location - Location to initialize the map on. Might be an address string or an array with [latitude, longitude] or a google.maps.LatLngobject. Default is false which shows a blank map.
  • bounds - Whether to snap geocode search to map bounds. Default: true if false search globally. Alternatively pass a custom LatLngBounds object
  • detailsAttribute - The attribute's name to use as an indicator. Default: "name"
  • mapOptions - Options to pass to the google.maps.Map constructor. See the full list here.
  • mapOptions.zoom - The inital zoom level. Default: 14
  • mapOptions.scrollwheel - Whether to enable the scrollwheel to zoom the map. Default: false
  • mapOptions.mapTypeId - The map type. Default: "roadmap"
  • markerOptions - The options to pass to the google.maps.Marker constructor. See the full list here.
  • markerOptions.draggable - If the marker is draggable. Default: false. Set to true to enable dragging.
  • markerOptions.disabled - Do not show marker. Default: false. Set to true to disable marker.
  • maxZoom - The maximum zoom level to zoom in after a geocoding response. Default: 16
  • componentRestrictions - Option for Google Places Autocomplete to restrict results by country. See the docs
  • types - An array containing one or more of the supported types for the places request. Default: ['geocode'] See the full list here.
  • blur - Defaults to false. When enabled it will trigger the geocoding request whenever the geofield is blured. (See jQuery .blur())

Events

You can subscribe to events of the geocode plugin by using the default jQuery syntax:

$("input")
  .geocomplete()
  .bind("geocode:result", function(event, result){
    console.log(result);
  });

The following events are supported:

  • "geocode:result" - Geocode was successful. Passes the original result as described here.
  • "geocode:error" - Fired when the geocode returns an error. Passes the current status as listed here.
  • "geocode:multiple" - Fired immediately after the "result" event if multiple results were found. Passes an array of all results.
  • "geocode:dragged" - Fired when the marker's position was modified manually. Passes the updated location.
  • "geocode:click" - Fired when 'click' event occurs on the map. Passes the location where the click had place.
  • "geocode:mapdragged" - Fired when the map bounds are modified by dragging manually. Passes the location of the current map center.
  • "geocode:idle" - Fired when the map becomes idle after panning or zooming. Passes the location of the current map center.

Methods and Properties

You can access all properties and methods of the plugin from outside. Simply add a string as the first argument to the .geocomplete method after you initialized the plugin.

Example:

// Initialize the plugin.
$("input").geocomplete({ map: ".map_canvas" });

// Call the find method with the parameter "NYC".
$("input").geocomplete("find", "NYC");

// Get the map and set a new zoom level.
var map = $("input").geocomplete("map");
map.setZoom(3);

Address and Places Specific Component Types

The following types are supported by the geocoder and will be passed to the provided form or container:

street_address, route, intersection, political, country, administrative_area_level_1, administrative_area_level_2, administrative_area_level_3, colloquial_area, locality, sublocality, neighborhood, premise, subpremise, postal_code, natural_feature, airport, park, point_of_interest, post_box, street_number, floor, room, lat, lng, viewport, location, formatted_address, location_type, bounds

For more information about address components visit http://code.google.com/apis/maps/documentation/geocoding/#Types

Additionally the following details are passed when the Places API was requested:

id, url, website, vicinity, reference, rating, international_phone_number, icon, formatted_phone_number

More information can be found here: https://developers.google.com/maps/documentation/javascript/places#place_details_responses

About

Developed by Martin Kleppe at Ubilabs.

geocomplete's People

Contributors

aemkei avatar coolagin avatar cpa99dcs avatar cuchac avatar danielochoa avatar diazruy avatar hinshun avatar jpsirois avatar jumski avatar klausi avatar macweber avatar mbertheau avatar mirceapricop avatar robertodecurnex avatar tylerpearson avatar vit-lebediev avatar vitaly avatar zipang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

geocomplete's Issues

Using find button when user does not select from list

I am having an issue. If the user types 'Denver, CO' without selecting the dropdown prompted value, I am unable to get the form fields populated for geocoding. Example:

$("#Location").geocomplete({ details: "#searchFormLocation", country: 'US', autoFocus: true }

$("#buttonSearchLocation").click(function () {
$("#Location").trigger("geocode");
$("#searchFormLocation").submit();
});

What am I doing wrong?

Filling Multiple forms or different inputs with details from respective auto suggests

Filling Multiple forms or different inputs with details from respective auto suggests,
doesn't sound good but that is what i want to achieve..

I have to address inputs on a form, each autosuggesting addresses.. I want to capture details from autosugget DETAILS results to other input fields.

and the same for the second input,

But remeber they both originate from same forms..

Is this possible ?
if you can understand it.. !

Dynamically change country limiting.

Hi guys,
Could I ask if there is anyway to change the limiting country dynamically after instantiation of the component?

Basically I default the plugin to limit geocoding to 'za' (South Africa), my interface allows the user to select another country from a separate dropdown. I want to update the restriction with the new ISO2 without recreating the object so that any further geocode calls are limited to the new country.

Any help would be appreciated.

David.

Jquery colorbox

There are not place suggestions if an input is in popup like Jquery Colorbox.

Adding own markers on the default map

I use Geocomplete with a map. But, when I get results (places) from my database with latitudes and longitudes (example, store locator), I want to add them on the map. How can I do that?

Inconsistent zoom behavior

When using the zoom control on

http://ubilabs.github.com/geocomplete/examples/location.html

the center marker moves to the upper left with each increase in zoom.

When using the zoom control on

http://ubilabs.github.com/geocomplete/examples/form.html

the center marker moves in an unpredictable direction with the first increase in zoom. With each further increase in zoom, the center marker follows a straight line until it moves out of the boundary.

Is there something wrong with the center method?

detect zero results

Is there a way to detect to zero results from google places search using this plugin

Intelligently enable enter keypress

On line 165 of jquery.geocomplete.js the enter keypress is disabled to block it from submitting the parent form. That's OK, however for my project I'd like to do is detect whether or not the dropdown matches are visible; and only then block the enter keypress. I.e. allow the enter key to submit the form if we're not in the middle of choosing from the autocomplete. I believe it would involve checking $('.pac-container:visible'). Is this something I should post a pull request for or just keep to myself?

Thanks for the helpful plugin!

Zoom in and out with mouse scroll ?

Hi,

Just wondering whether its possible to:

  1. Setup the controls on the map
  2. Scroll with the mouse wheel in and out for zooming ?

I can't seem to find how to do that ?

geocomplete not working inside facebox!

the geocoplete seems to work fine
but when in trigger it to a inputbox which loads inside a facebox it dosent work
can u guys help me with this?
thanks in advance

Inaccurate Location Initialize

If I use Latitude and Longitude coordinates to set the initial 'location' on the map, the marker is not positioned at the exact same Latitude and Longitude.

For Example:

The coordinates for the International Convention Center (ICC), Durban, South Africa are:
Latitude: -29.852508775404086
Longitude: 31.029730119973237

var setloc = new google.maps.LatLng(-29.852508775404086,31.029730119973237);
$("#geocomplete").geocomplete({
map: ".map_canvas",
details: "form",
location: setloc,
markerOptions: {
draggable: true
}
});

The above map is drawn but the marker is positioned at:
Latitude: -29.8527608
Longitude: 31.029846799999973

I initially thought it may have to do with the zoom factor? When getting the original Lat/Lon coordinates using the 'dragable' marker, I ensure I zoomed in on the ICC as far as it would allow. But no change.

I also used the original coordinates in Google Maps itself. -29.852508775404086,31.029730119973237. The map it delivered 'rounded' the coordinates to -29.852509, 31.029730 and placed the marker on the exact same position as the original coordinates ie. -29.852508775404086,31.029730119973237

Constructor ignores zoom setting when location is a string

When I pass in a value for zoom in the mapOptions when calling the geocomplete constructor with a location that is a string, the zoom value appears to be ignored.

I examined the source code at

http://ubilabs.github.com/geocomplete/docs/

but I could see no obvious reason why this is happening.

autosuggest mismatch

when i'm entering 'Россия, Новосибирская область, Новосибирск, улица Серебренниковская 4/1' into auto-suggest input and chosing first available suggestion option i'm getting completely different value in input field instead of chosen variant. is it a bug or feature?

Pressing 'enter' does not always return correct result in autocomplete list.

When you press 'enter' rather than selecting an item from the autocomplete list, the plugin initiates a geocode search. If you've added biasing or a region, this is passed onto the geocode search. Unfortunately, whatever mechanism the geocode search uses is not the same as the autocomplete list. This means that on some occasions the result returned is not the same as the first item on the list.

The only way I've found to fix this, is by extracting the first item from the ".pac-container". Changing the placeChanged function as follows fixes this:

            this.find($(".pac-container .pac-item:first").text() || place.name);

Streetaddress plus number

Is it possible to fill the an input field with the streetname (route) and streetnumber (street_number)?

Thanks.

Keypress on enter does not submit the form

After selecting an autocompletion entry, i press enter to get it as value for my geocoded input. When i press enter now, i expect to submit the inputs form. In fact it doesn't happen anything.

Returning place types by location search

Is it possible to force the geocomplete to return places (as defined by the "type: [ ]" option) based on a location search?

For example: A user types in "60605" and hits "search," and as in the multiple results example, a list of places matching the type (defined by me), and falling within a specified radius of the search location (60605) is appended.

Thanks for a great plugin! Whether this is possible or not, it has made working with the google maps api so much easier!

.geocomplete("find", "NYC") and bind not working

if you do a bind on a .geocomplete("find", "NYC") throws javascript error

TypeError: $("#formatted_address").geocomplete("find", "NYC") is undefined
[Break On This Error]

      $(function(){
     $("#formatted_address")
            .geocomplete("find", "NYC")
            .bind("geocode:result", function(event, result){
              console.log(result);
            });

      });

Biasing search results by location only works when map is displayed

I am trying to provide more relavent address suggestions by biasing them based on a certain location. This works perfectly when a map is displayed, but I have no use for the map. I guess I always have the option of just hiding the map via css, but I was hoping that geocomplete could update the location feature to work without an actual map.

Can't seem to see Places API in action, only geocoding

Hi All,
I don't know what I get wrong with the plug-in, but either through the examples or by running the code locally I feel I only get geocoding results.

To verifiy each time, I try to add the name of a bar in NYC which I know only gets returned by the places api: "White Star, Essex Street".

Is there some type configuration option I'm not enabling or something I am missing?

Thanks a lot in advance!

No "street_address" in result

    fillDetails: function(result){

"result" object doesn't have "street_address" in "address_components", it is set as a separate property of result - "name".
If you just typed in search term and submitted, "name" is being returned. If you click "find" again, "name" is not being returned.

I made a quick "fix" to replace "street_address", on line 338 I added following:

        street_addr: result.formatted_address.split(',')[0],

So lines 335-339 look like this:

      // Add infos about the address and geometry.
      $.extend(data, {
        formatted_address: result.formatted_address,
        street_addr: result.formatted_address.split(',')[0],
        location_type: geometry.location_type || "PLACES",

And added "street_addr" on line 65:

    "formatted_address street_addr location_type bounds").split(" ");

Set Current location

I want to know how can i set the current location in your js I already have current location latitude and longitude of current location reply me as sson as possible

Make geocoding types configurable

It would be nice to make geocoding types configurable so that we can populate input elements where we have name attributes different from i.e. "route" or "street_address".

Alter "input" field value after .bind event fired

I want to reset "input" field value that I use with .geocomplete function. After I run this $("#txtAddress1").bind("geocode:result", function(event, result)
{ set value...}
it changes the value back to whatever was retrieved from DB

placeholder

After initialization of geocomplete, input text value equals placeholder value in IE9. I haven't found a form to disable this behavior.

Default location with marker

The marker on default location only happens when you call it with string, but it would be nice if it also showed when you call it with LatLng.
Example:

defLocation = new window.google.maps.LatLng($lat.val(), $lng.val());
$this.geocomplete({map: '#map', location: defLocation, markerOptions: {draggable: true}});

multiple markers

When trying to use same map for 2 o more inputs result in incorrect map flash and display like overlay of results. Is it possible to add multiple markers to same map?

It should be possible to set bounds dynamically

I'm using the geocomplete with a Google Map that I'm managing entirely myself (i.e. not specifying it as a constructor parameter). However, I wish to bias the results of the autocomplete so that it corresponds with the current viewport.

I can't seem to be able to do this using .geocomplete() after it has been initialized the first time, so I'm having to use this workaround:

        // Bias autocomplete to bounds
        var underlying = $.data(self.autocomplete.get(0), 'plugin_geocomplete');
        underlying.options.bounds = self.map.getBounds();

Would it be possible to add a method that allows this to be done dynamically?

locale

There is no way to configure locale used by georeference.

Retain zoom after dragging

After dragging the marker, and calling "find", the text and the map are updated OK.

But the zoom level is reset to its original value. How can I retain the changed zoom value, after the map is updated?

Load place as example

I am trying to get the examples to load places - but this seems to acknowledge street names/towns only.

I have put a couple of examples into this page:
http://mymusicwall.co.uk/mapform.asp

If you search example "The Emporium, Belvoir Road, Coalville, United Kingdom" and then select the first result, the map selects the correct location along with the correct address & URL.

If we send this same string in as example - only the street is selected and no URL is returned. Is there any way I can get the examples to work in the same way?

Map in Twitter Bootstrap Modal

My first post, so just want to say "Awesome Plugin!!!"

I use twitter bootstrap and open a modal in which I load the map.
The map itself looks fine, but the marker (and +/- control on the left) seems to be stretch inwards, making the marker really small.

I'm only setting the height of the map for now:

screenshot

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.