how to handle manual clearing in google.maps.places. API - google-maps

I am using google.maps.places.API to provide a location search to the user.
When the user types and selects a location, I am catching the location coordinates in a variable(center hidden element) and using it for processing. However when the user is not satisfied, they may want to blank out the location input element manually and try to search by other options. In this case I want to clear of the lat and lng variables location input and thus the center input element values. I have tried to capture the onBlur event of the location search box, but not able to clear these variables it.
<script>
var autocomplete;
function initialize() {
var input = (document.getElementById('location'));
var options = {
types: ['(cities)']
};
autocomplete = new google.maps.places.Autocomplete(input,options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
var val = place.geometry.location;
document.getElementById('center').value = val;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Please advice how do I clear of the input element location( and thus element center ). Or am I missing a vital point in the code.

Related

Meteor and Google Place Autocomplete - InvalidValueError: not an instance of HTMLInputElement

I'm looking to use Google Place Autocomplete on one of my Meteor App Input.
When I initialize a session, I have an InvalidValueError: not an instance of HTMLInputElement, but when I refresh the page one time, the autocomplete works well.
What do I need to change on my code in order to have autocomplete working on first session?
My code:
if (Meteor.isClient) {
window.onload = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),{types:['geocode']}
);
google.maps.event.addListener(autocomplete,'place_changed',function(){
var place = autocomplete.getPlace();
});
};
}
Thanks for your help.
Call below code on-focus of input element.
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),{types:['geocode']}
);
You should try using Template instance:
Template.autocomplete.onRendered(function() {
// Your autocomplete function
// var autocomplete = ...
});
My template name is "autocomplete" in this example.

Google Maps Data Layer, Click on geometry programmatically

I have a google map where I load geometry data to the data layer using geoJSON. I bind to the following event in the data layer.
map.data.addListener('click', function (event) { console.log(event);});
How can I trigger this event manually? I know I can trigger the click event on a marker manually, but it is triggered through google.maps.event.
That should be done with google.maps.event.trigger.
Try this (not sure):
// invoke a click
google.maps.event.trigger(map.data, 'click');
While Emmanuel's answer is technically correct, I would like to expand on it because I struggled for 2-3 hours to get this working.
In my code, I have a predefined click event function which was using feature object.
Here is my click event where I have used feature object:
transLayerData.addListener('click', function (event) {
var lfeature = event.feature;
var html = lfeature.getProperty('popupInfo');
infowindow.setContent(html);
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infowindow.open(myMap);
});
If you are using a feature object in your predefined data layer click function (like above) , it is important that you pass the feature object and you create an event object with feature object in it.
Here is my code which gets the lat and long out of feature object and creates an event object:
var featureGeometry = feature.getGeometry();
var lsType = featureGeometry.getType();
var isLineData = false;
var lsType = featureGeometry.getType();
if ((lsType == 'LineString') || (lsType == 'MultiLineString') || (lsType == 'LinearRing') || (lsType == 'Polygon') | (lsType == 'MultiPolygon')) {
isLineData = true;
}
var featurePosition;
if (isLineData) {
// will center the map on the first vertex of the first LineString
var tmp = featureGeometry.getAt(0);
featurePosition = featureGeometry.getAt(0);
// following will set line's storke weight to 10
feature.setProperty('strokeWeight', 10);
} else{
featurePosition = featureGeometry.get();
}
myMap.setZoom(10);
myMap.setCenter(featurePosition);
var llat = featurePosition.lat();
var llong = featurePosition.lng();
// Creating event with the feature object is important. Especially if you have your very own feature click method defined
var lEvent = {
stop: null,
latLng: new google.maps.LatLng(llat, llong),
feature: feature,
}
// transLayerData is your data layer object.
// This is how I have defined my translayer object:
// transLayerData = new google.maps.Data({ map: myMap });
if (!isLineData) {
google.maps.event.trigger(transLayerData, 'click', lEvent);
} else {
google.maps.event.trigger(transLayerData, 'mouseover', lEvent);
}
}

google places autocomplete restrict to particular area

My requirement is to get google places autocomplete suggestion only for Bangalore places, but I am not getting places only for Bangalore or within mention latitude longitude.
I want to retireve only below image places in autocomplete textfield.
can someone plz suggest how to achieve the same and where I am going wrong.
Javascript:
<script type="text/javascript">
function initialize1() {
var southWest = new google.maps.LatLng( 12.97232, 77.59480 );
var northEast = new google.maps.LatLng( 12.89201, 77.58905 );
var bangaloreBounds = new google.maps.LatLngBounds( southWest, northEast );
var options = {
bounds: bangaloreBounds,
types: ['(cities)'],
componentRestrictions: {country: 'in'}
};
var input = document.getElementById('searchTextFieldTo');
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize1);
</script>
TextField:
<input type="text" id="searchTextFieldTo" class="ui-timepicker-hour" style="width:350px;text-align:left;font-style:italic;" placeholder="Enter To location" autocomplete="on" />
Google Provides two ways to achieve this. If you are not satisfied because in countries like India it do not work well, because states and provisions here do not have rectangular or structure boundaries.
1.LatLngBounds (LatLng southwest, LatLng northeast): Where you can give latitude and longitude to form an rectangle.
2. Location (Lat,Lng) & Radius: Where you can give latitude and longitude to form a circle.
But the problem with these approaches they do not provide expected results if you are from countries like India, where states and provisions are not in structured shapes (Rectangular) as in USA.
If you are facing same issue than there is an hack.
With jQuery/Jacascript, you can attach functions which will consistently maintain city name in text input which is bounded with Autocomplete object of Places API.
Here it is:
<script>
$(document).ready(function(){
$("#locality").val(your-city-name) //your-city-name will have city name and some space to seperate it from actual user-input for example: “Bengaluru | ”
});
$("#locality").keydown(function(event) { //locality is text-input box whixh i supplied while creating Autocomplete object
var localeKeyword = “your-city-name”
var localeKeywordLen = localeKeyword.length;
var keyword = $("#locality").val();
var keywordLen = keyword.length;
if(keywordLen == localeKeywordLen) {
var e = event || window.event;
var key = e.keyCode || e.which;
if(key == Number(46) || key == Number(8) || key == Number(37)){
e.preventDefault();
}//Here I am restricting user to delete city name (Restricting use of delete/backspace/left arrow) if length == city-name provided
if(keyword != localeKeyword) {
$("#locality").val(localeKeyword);
}//If input-text does not contain city-name put it there
}
if(!(keyword.includes(localeKeyword))) {
$("#locality").val(localeKeyword);
}//If keyworf not includes city name put it there
});
</script>
(Image:) Before This Hack
(Image:) After This hack
As mentioned in my answer here:
It is currently not possible to restrict results to a specific locality. You can use bounds as you have done so above to bias results towards, but not restricted to places contained within the specified bounds.
If you believe restriction by locality would be a useful feature please file a Places API - Feature Request.
EDIT:
As per 2018-07 it's possible to define the types of places to be retrieved, like cities (which are locality or administrative_area3 according to the API). Check out full answer here.
I think you can try this.
var bangaloreBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(12.864162, 77.438610),
new google.maps.LatLng(13.139807, 77.711895));
var autocomplete = new google.maps.places.Autocomplete(this, {
bounds: bangaloreBounds,
strictBounds: true,
});
autocomplete.addListener('place_changed', function () {
});
Note form xomena:
strictBounds option was added in version 3.27 of Maps JavaScript API which is currently (January 2017) the experimental version.
function initialize() {
var bangaloreBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(12.864162, 77.438610),
new google.maps.LatLng(13.139807, 77.711895));
var options = {
bounds: bangaloreBounds,
componentRestrictions: {country: 'in'},
strictBounds: true,
};
var input = document.getElementById('autocomplete');
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
As in the current documentation for Google javascript Places API here, you can define an array of types of places to be retrieved. In the example below, I set it to retrieve only cities (which are, according to the API, locality or administrative_area3). You can set it retrieve regions, addresses, establishments and geocodes as well.
function initMap() {
var input = document.getElementById('my-input');
var options = {
types: ['(cities)']
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
// the rest of the code ...
}

Google Map API V3 — How to prevent mouse click event for a marker when user actually has double clicked

I have a marker on the map to which I want to bind two events:
click
dblclick
I want to do the following:
When user clicks on the marker, map should zoom-in and will show
more detailed map.
I want to bind 'dblclick' event to the same marker so that it will
load some third-party reports in adjacent 'div' element.
In other words, I want it to behave differently when user clicks or dblclicks. But the problem is, when I bind both these event to marker and user 'double clicks' the marker, 'click' handler is getting fired, which I don't want to let it happen.
Is it true that, when user double-clicks, click event is also fired? If so, how to prevent it from triggering 'click' event when user actually double-clicked?
Is there any way so that I can do different things on either click and double-click event of the marker?
It's a known nuance of the api, you need to install a click counter timeout, like this:
function createMap2() {
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map2"), myOptions);
var doubleClicked=false;
var clickEvent;
google.maps.event.addListener(map, 'dblclick', function(event) {
doubleClicked=true;
});
function handleClick() {
if (!doubleClicked) {
infoWindow.setPosition(clickEvent.latLng);
infoWindow.setContent(createInfo(clickEvent));
infoWindow.open(map);
}
}
google.maps.event.addListener(map, 'click', function(event) {
clickEvent = event;
doubleClicked = false;
window.setTimeout(handleClick, 250);
});
}
Above code extracted from http://www.william-map.com/20100506/1/v3click.htm
Check out these links for more info:
https://groups.google.com/forum/?fromgroups=#!topic/google-maps-js-api-v3/YRAvYHngeNk
https://groups.google.com/forum/?fromgroups=#!topic/google-maps-js-api-v3/2MomDiLMEiw
You can use a pre-handler function that separates single from double clicks. In this case, the second click must come within 500 miliseconds of the first one:
//Global vars
var G = google.maps;
var clickTimeOut = null;
G.event.addListener(marker,'click',mClick);
function mClick(mev) {
if (clickTimeOut) {
window.clearTimeout(clickTimeOut);
clickTimeOut = null;
doubleClick(mev);
}
else {
clickTimeOut = window.setTimeout(function(){singleClick(mev)},500);
}
}
function doubleClick(mev) {
// handle double click here
}
function singleClick(mev) {
window.clearTimeout(clckTimeOut);
clickTimeOut = null;
// handle single click here
}
mev is the mouseEvent object that the event handlers receive as parameter.

limiting google maps autocomplete to UK address only

I've been looking at the example on:
http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html
and have decided to incorporate it into my site.
Is it possible to limit the addresses to UK addresses only?
Try this:
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'tr'}//Turkey only
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
You can't strictly/hard limit the locations that it finds, although there is a feature request in the system to do so, but you can set a 'bias' on the results. It's passed in as an argument to the autocomplete method as a google maps bounds object. Autocomplete will then favor locations within those boundaries. Note, however, that since this isn't a hard boundary, if there are matches for the search outside the boundaries it will return those.
From my usage it seems a bit buggy and can use some improvement - especially considering that anything outside your boundary is not tagged by proximity at all, so something one block outside the boundary is just as likely to show as something 1000 miles outside, so make sure you play around with getting the boundaries working right.
You can intercept the JSONP results that are returned by the google.maps.places.Autocomplete functionality and use them as you see fit, such as to limit by country and display the results.
Basically you redefine the appendChild method on the head element, and then monitor the javascript elements that the Google autocomplete code inserts into the DOM for JSONP. As javascript elements are added, you override the JSONP callbacks that Google defines in order to get access to the raw autocomplete data.
It's a bit of a hack, here goes (I'm using jQuery but it's not necessary for this hack to work):
//The head element, where the Google Autocomplete code will insert a tag
//for a javascript file.
var head = $('head')[0];
//The name of the method the Autocomplete code uses to insert the tag.
var method = 'appendChild';
//The method we will be overriding.
var originalMethod = head[method];
head[method] = function () {
if (arguments[0] && arguments[0].src && arguments[0].src.match(/GetPredictions/)) { //Check that the element is a javascript tag being inserted by Google.
var callbackMatchObject = (/callback=([^&]+)&|$/).exec(arguments[0].src); //Regex to extract the name of the callback method that the JSONP will call.
var searchTermMatchObject = (/\?1s([^&]+)&/).exec(arguments[0].src); //Regex to extract the search term that was entered by the user.
var searchTerm = unescape(searchTermMatchObject[1]);
if (callbackMatchObject && searchTermMatchObject) {
var names = callbackMatchObject[1].split('.'); //The JSONP callback method is in the form "abc.def" and each time has a different random name.
var originalCallback = names[0] && names[1] && window[names[0]] && window[names[0]][names[1]]; //Store the original callback method.
if (originalCallback) {
var newCallback = function () { //Define your own JSONP callback
if (arguments[0] && arguments[0][3]) {
var data = arguments[0][4]; //Your autocomplete results
//SUCCESS! - Limit results here and do something with them, such as displaying them in an autocomplete dropdown.
}
}
//Add copy all the attributes of the old callback function to the new callback function. This prevents the autocomplete functionality from throwing an error.
for (name in originalCallback) {
newCallback[name] = originalCallback[name];
}
window[names[0]][names[1]] = newCallback; //Override the JSONP callback
}
}
//Insert the element into the dom, regardless of whether it was being inserted by Google.
return originalMethod.apply(this, arguments);
};
James Alday is correct:
http://code.google.com/apis/maps/documentation/javascript/places.html#places_autocomplete
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(49.00, -13.00),
new google.maps.LatLng(60.00, 3.00));
var acOptions = {
bounds: defaultBounds,
types: ['geocode']
};
it is somewhat annoying as searching for Durham gives Durham, North Carolina as the second result, regardless of how you try to persuade it to region bias - you can set it to viewport map bounds and it'll still try to suggest NC state... The jQuery solution can be found here, but doesn't seem to give as many results as the v3 API.
http://code.google.com/p/geo-autocomplete/
The best way you would go about doing this, is to query the places api yourself and appending the queried string with your country. Or, of course, use the geo-autocomplete jQuery plugin.
Just change the google domain for the maps to your country domain and it will automatically search within your country only:
So:
http://maps.google.com/maps/api/geocode/xml?address={0}&sensor=false&language=en
To:
http://maps.google.nl/maps/api/geocode/xml?address={0}&sensor=false&language=nl
Try something like this.
// Change Bangalore, India to your cities boundary.
var bangaloreBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(12.864162, 77.438610),
new google.maps.LatLng(13.139807, 77.711895));
var autocomplete = new google.maps.places.Autocomplete(this, {
bounds: bangaloreBounds,
strictBounds: true,
});
autocomplete.addListener('place_changed', function () {
});
I find that if you set the map to roughly where you want then set bounds to it, the search finds places in that area first. You do not to physically show the map.
It works better than giving random overseas addresses first, setting to country does not work.
The code for autocomplete to get latln is:
<div id="map_canvas"></div>
<input type="text" name="location" id="location" placeholder="Type location...">
<input type="text" name="loc_latitude" id="latitude">
<input type="text" name="loc_longitude" id="longitude">
and the JS is:
$(document).ready(function () {
var mapOptions = {
center: new google.maps.LatLng(52.41041560, -1.5752999),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var autocomplete;
autocomplete = new google.maps.places.Autocomplete((document.getElementById(searchInput)), {
types: ['geocode'],
});
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var near_place = autocomplete.getPlace();
document.getElementById('latitude').value = near_place.geometry.location.lat();
document.getElementById('longitude').value = near_place.geometry.location.lng();
});
});
$(document).on('change', '#'+searchInput, function () {
document.getElementById('latitude').value = '';
document.getElementById('longitude').value = '';
});
Not exactly what you asked for but it works for me.