Currently when you click on the autosuggest suggestion in the location field it just loads it into the input box. I want to make an adjustment to it, so when you click on the result in the autosuggest box, not only does it load its value into the input box but it also triggers the geocode. I cant get my head around how I would do this though, so I would appreciate some help.
This is the code: http://jsfiddle.net/njDvn/130/
<!-- Geocode -->
$(document).ready(function () {
var GeoCoded = { done: false };
autosuggest();
$('#myform').on('submit', function (e) {
if (GeoCoded.done) return true;
e.preventDefault();
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('location').value;
$('#myform input[type="submit"]').attr('disabled', true);
geocoder.geocode({
'address': address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
GeoCoded.done = true;
$('#myform').submit();
} else {
console.log("Geocode failed: " + status);
//enable the submit button
$('#myform input[type="submit"]').attr('disabled', false);
}
});
});
});
And the autosuggest:
<!-- AutoSuggest -->
function autosuggest() {
var input = document.getElementById('location');
var options = {
types: [],
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
What you could do instead is use only Places API library and simply listen for place_changed event like in this sample here:
https://developers.google.com/maps/documentation/javascript/places#getting_place_information
You can get the Geocode using: place.geometry.location
Related
I work as an intern with Ruby on Rails and yesterday I had to do something with Javascript (my javascript skills ARE AWFUL, I DON'T EVEN HAVE SKILLS with IT).
I implemented current location feature in a project, but I'd like to do it another way... the thig is kinda done, take a look:
function geolocationSuccess(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latlng = {lat: latitude, lng: longitude};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]){
var user_address = results[0].formatted_address;
document.getElementById("current_location").innerHTML = user_address;
}else {
console.log('No results found for these coords.');
}
}else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function geolocationError() {
console.log("please enable location for this feature to work!");
}
$(document).on("ready page:ready", function() {
$("#current-location").on("click", function(event) {
event.preventDefault();
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
});
All right, I know it all happens when I click the button with Id="current-location", but I'd like it to happen automatically when the page loads, how can I do it?
Simply insert the code you want executed inside of a $(document).ready( block:
$(document).ready(function() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
} else {
alert("Geolocation not supported!");
}
});
On a side note, I would recommend not naming a function variable event since event is a keyword. The standard convention for passing event to a function is to use e. For example:
$('#someId').on('click', function(e) {
e.preventDefault();
//do something
});
This is the sample code , Very basic , but 'place_changed' is not triggering in iOS
var input = document.getElementById('autocomplete');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function(){
mylocation = autocomplete.getPlace();
alert(mylocation);
})
tried these solutions :
1 : removed autocomplete from listener
google.maps.event.addListener('place_changed', function()
2 : added tappable because of pac-item is not a button , link .
let list1 = document.querySelectorAll(".pac-item,.pac-container");
console.log('pacIt', list1);
for (let i = 0; i < list1.length; ++i) {
list1[i].setAttribute('tappable', 'true');
}
3: added needsclick
let list2 = document.querySelectorAll(".pac-item, .pac-item span");
console.log('pacIt', list2);
for (let i = 0; i < list2.length; ++i) {
list2[i].classList.add('needsclick');
}
And none of the solutions helped me to solve the issue.
Kindly anyone is having clean fix , please share .
Thanks in advance.
There is no Bug fix from Google
Hence created my own custom autocomplete
first, init the component :
this.customAutoComp = new google.maps.places.AutocompleteService(
{
componentRestrictions: { 'country': 'in' }
});
Next
this.customAutoComp.getQueryPredictions({ input: value }, (results, status) => {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(results);
}
});
Results will be populated on UI using UL, LI or any other cards style.
Click on Any address
public clickAddress(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
}
});
I'm developing a website using Wordpress and I'm using a theme that allows to insert custom post called "Property"; this features is handled inside a custom page template. Inside this page I can add the address of the property, which has the autocomplete geocoder suggestion. Here is the code:
this.initAutoComplete = function(){
var addressField = this.container.find('.goto-address-button').val();
if (!addressField) return null;
var that = thisMapField;
$('#' + addressField).autocomplete({
source: function(request, response) {
// TODO: add 'region' option, to help bias geocoder.
that.geocoder.geocode( {'address': request.term }, function(results, status) {
//$('#city').val(results.formatted_address);
response($.map(results, function(item) {
$('#city').val(item.formatted_address);
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
};
}));
});
},
select: function(event, ui) {
that.container.find(".map-coordinate").val(ui.item.latitude + ',' + ui.item.longitude);
var location = new window.google.maps.LatLng(ui.item.latitude, ui.item.longitude);
that.map.setCenter(location);
// Drop the Marker
setTimeout(function(){
that.marker.setValues({
position: location,
animation: window.google.maps.Animation.DROP
});
}, 1500);
}
});
}
When an address is clicked, the maps draw a maker with the coordinates received. I would like to extract the city from the address clicked and put that value on another input field. How can I do that? Thanks!
looking at documentation
you need to access address_components and look for type locality, political, so something like this:
var city = '';
item.address_components.map(function(e){
if(e.types.indexOf('locality') !== -1 &&
e.types.indexOf('political') !== -1) {
city = e.long_name;
}
});
$('#city').val(city);
I am using the google places api in my website.When i focus on the input field and start writing the autocomplete works fine but when i press enter it gets submitted without the value.I get the error: "cannot read property "location" of undefined".
Javascript:
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var input = document.getElementById('main_search');
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(22.4667, 88.3067),
new google.maps.LatLng(22.8667, 88.467));
var options = {
bounds: defaultBounds,
types: ['establishment'],
componentRestrictions: {
country: 'in'
}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
document.getElementById('city').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
});
}
</script>
i am using the get method and i don't get any value.when i use mouse and click on submit button everything works fine.
Temporary fix
Disable the enter default when pac-container (autocomplete dropdown) is visible
$('#search-entry').keydown(function(e) {
if (e.which == 13 && $('.pac-container:visible').length) return false;
});
This is my first JavaScript I have tried to put together but I am not having a lot of luck.
This is what the script should do: Geocode an address either by clicking on an autosuggested location or by clicking search button if we do not have the result already from clicking autosuggestion. Then submit the form.
I am not having much luck, it seems I have mucked up my bracketing on the script because no matter what I do it complains about exceptions.
This is my code:
geocode();
// SET COOKIE FOR TESTING PURPOSES
$.cookie("country", "US");
// GEOCODE FUNCTION
function geocode() {
var coded = false;
var input = document.getElementById('loc');
var options = {
types: ['geocode']
};
var country_code = $.cookie('country');
if (country_code) {
options.componentRestrictions = {
'country': country_code
};
}
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
processLocation();
});
// ON SUBMIT - WORK OUT IF WE ALREADY HAVE THE RESULTS FROM AUTOCOMPLETE FUNCTION
$('#searchform').on('submit', function(e) {
e.preventDefault();
if(coded = false;) {
processLocation();
}
else {
$('#searchform').submit();
}
});
// CHECK TO SEE IF INPUT HAS CHANGED SINCE BEING GEOCODED
// IF "CODED" VAR IS FALSE THEN WE WILL GEOCODE WHEN SEARCH BUTTON HIT
$("#loc").bind("change paste keyup", function() {
var coded = false;
});
};
// GEOCODE THE LOCATION
function processLocation(){
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('loc').value;
$('#searchform input[type="submit"]').attr('disabled', true);
geocoder.geocode({
'address': address
},
// RESULTS - STORE COORDINATES IN FIELDS OR ERROR IF NOT SUCCESSFUL
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var coded = true;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
var coded = false;
$('#searchform input[type="submit"]').attr('disabled', false);
alert("We couldn't find this location")
}
});
}
Where have I gone wrong?
PS: Because this is my first script, I am happy to receive feedback if I have made any poor choices in the design of it. I really want to make my first script as cleanly coded as possible.
There is an syntax error
if(coded = false;) {
should be
if(coded == false) {
Checking the console would have told you such a thing and also the place WHERE the error occured.... Here's your fixed fiddle