I am trying to use the autocomplete jquery API. The issue is I want to trigger a function or a set of code once I selected an item but i keep getting undefined items.
Here my code:
function init()
{
var input = document.getElementById('event_address');
var options =
{
types: ['geocode']
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
// event triggered when drop-down option selected
select: function(event, ui) {
var address = document.getElementById(event_address).value;
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
alert(results[0].geometry.locations);
}
});
}
}
Here my errors:
Uncaught SyntaxError: Unexpected token (
Thanks
First, I believe what you are referring to is jqueryUI's autocomplete widget. The select method fires when an autocomplete selection has been made. I'm assuming what you're trying to do would be to display the coordinates of a geographical region chosen from the auto complete list.
you would need to do something like this:
$('#inputbox').autocomplete({
select: function(event, ui){
// code to get selection
var address = $('#inputbox').text();
//assuming your geocode is correct
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
alert(results[0].geometry.locations);
}
});
}
});
For more info, see the autocomplete documentation: http://api.jqueryui.com/autocomplete/#event-select
Related
This question already has answers here:
check if location setting has been turned off in users browser
(2 answers)
Closed 3 years ago.
I'm trying to make an HTML element visible if the end user hasn't agreed to let the browser know their location. However, my current code isn't working (nor is the console log) when declining the browser's request. But when allowing the browser to access my location, the API call to Google Places works.
To summarise: If a user declines the browser's request, I want the visibility of geolocationunavail to be visible, rather than hidden.
HTML
<div id="geolocationunavail">
<p>Don't want to share your location?</p>
<p><span>That's cool.</span> Type a location below.</p>
</div>
CSS
#geolocationunavail {
visibility: hidden;
}
JS
function getUserLocation() {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position) {
document.querySelector("#longitude").value = position.coords.longitude;
document.querySelector("#latitude").value = position.coords.latitude;
var lng = position.coords.longitude;
var lat = position.coords.latitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
document.querySelector("#citysearch").value = address;
}
});
});
} else {
console.log("Geolocation is not supported by this browser.");
document.getElementById("geolocationunavail").style.display = "visible";
}
}
It looks like you have 2 different problems, so I will address them both:
First, your geolocation function is not working as expected. This is happening because you are not using the function correctly. You would not want to use an else statement to say that geolocation is not working, because geolocation will always "work" since it is called successfully regardless of the user input. Even if the user selects "block" the function technically "worked" and therefore will not run the else statement.
Second, your visibility is not toggling correctly. There are 2 ways you can fix this. You can either make it a class and use classList.toggle("myClass"), or you can do document.getElementById('geolocationunavil').style.visibility = 'visible';
Both of these put together will result in:
function getUserLocation() {
navigator.geolocation.getCurrentPosition(
position => {
document.querySelector("#longitude").value = position.coords.longitude;
document.querySelector("#latitude").value = position.coords.latitude;
var lng = position.coords.longitude;
var lat = position.coords.latitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
document.querySelector("#citysearch").value = address;
}
});
},
err => {
console.log("Geolocation is not supported by this browser.");
document.getElementById("geolocationunavail").style.visibility = "visible";
})
}
I can't get autocomplete input with jquery .val(), because .val() only returns input value which was typed by myself but not what was added by autocomplete.
jquery .val() only returns full value if make changes on other fields.
I use google maps autocomplete for address, and than I pass that address to google maps api to get distances between two addresses. Problem is that this "start = $('#id_rent_delivery_address').val()" only gets address part which is typed manually but not autocompleted.
Maybe you have any ideas how I could fix it?
My code:
<script>
$(document).ready(function() {
initAutocomplete();
});
var autocomplete, autocomplete2;
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('id_rent_withdraw_address')),
{types: ['geocode']});
autocomplete2 = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('id_rent_delivery_address')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
}
</script>
<script type="text/javascript">
$(document).on('change', '#rent-confirm-form', function() {
var start = $('#id_rent_delivery_address').val();
var end = $('#id_rent_withdraw_address').val();
GetRoute(start, end);
});
function GetRoute(start, end) {
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [start],
destinations: [end],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
console.log(distance);
console.log(duration);
console.log(start);
console.log(end);
} else {
console.log("Unable to find the distance via road.");
}
});
}
</script>
Solved by myself. Just simulated form change with jquery trigger method.
$( "#anyInput" ).trigger("change");
In my AngularJS project I am using the following code to get a device's GPS co-ordinates:
// when user clicks on geo button
$scope.getGeoLocation = function() {
var geocoder = new google.maps.Geocoder();
window.navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.position = position;
var latlng = new google.maps.LatLng($scope.position.coords.latitude, $scope.position.coords.longitude);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$scope.searchstring = results[2].formatted_address;
$location.search('s', $scope.searchstring);
$location.search('p', 1);
$location.search('geo', true);
$route.reload();
}
});
});
}, function(error) {
$scope.error = error;;
});
};
The problem is when location services is turned off on an iPhone 6, there is a no error created to inform the user that they need to turn on location services.
Does any one know how I can amend the code above to trigger an error in this scenario? Any help would be much appreciated.
As pointed out in this post Is there a way to check if geolocation has been DECLINED with Javascript?, you can pass a second callback to getCurrentPosition which will get called if the permission is declined.
Thanks for pointing me in the right direction unobf. Please find attached the code (with updated error handling) in case any one stumbles across this.
// when user clicks on geo button
$scope.getGeoLocation = function() {
var geocoder = new google.maps.Geocoder();
window.navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.position = position;
var latlng = new google.maps.LatLng($scope.position.coords.latitude, $scope.position.coords.longitude);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$scope.searchstring = results[2].formatted_address;
$location.search('s', $scope.searchstring);
$location.search('p', 1);
$location.search('geo', true);
$route.reload();
}
});
});
}, function(error) {
$scope.error = "";
// Check for known errors
switch (error.code) {
case error.PERMISSION_DENIED:
$scope.error = "This website does not have permission to use " +
"the Geolocation API.";
alert("Geo location services appears to be disabled on your device.");
break;
case error.POSITION_UNAVAILABLE:
$scope.error = "The current position could not be determined.";
break;
case error.PERMISSION_DENIED_TIMEOUT:
$scope.error = "The current position could not be determined " +
"within the specified timeout period.";
break;
}
// If it's an unknown error, build a $scope.error that includes
// information that helps identify the situation, so that
// the error handler can be updated.
if ($scope.error == "")
{
var strErrorCode = error.code.toString();
$scope.error = "The position could not be determined due to " +
"an unknown error (Code: " + strErrorCode + ").";
}
});
};
I have a form that is validated upon submission, inside the form submit a function is called, the submit continues and doesn't wait for the function to finish. How do I fix this?
var clientaddress=false;
function checkaddress(callback){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status != google.maps.GeocoderStatus.OK) {
clientaddress=false;
callback(false);
}
else if (status == google.maps.GeocoderStatus.OK) {
clientaddress=true;
callback(false);
}
}
jQuery(document).ready(function(){
jQuery("#submitOrder").submit(function(){
checkaddress(function(result) {
if (!result) {
jAlert("Please enter a valid address!");
jQuery("#address").focus();
isValidation = 0;
}
});
//other validation code that gets executed without waiting for checkaddress()
//submit page
})
I tried to make one function that calls both the address checker and a validation function, but still they do not wait for each other.
How can I solve this problem?
Because the geocode function is async! Use a callback:
function checkaddress(callback){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status != google.maps.GeocoderStatus.OK) {
callback(false)
} else if (status == google.maps.GeocoderStatus.OK) {
callback(true)
}
});
}
Then use this like:
checkaddress(function(result) {
if (result) {
//result true!
} else {
//result false!
}
//REST OF YOUR CODE GOES HERE, IF PUT OUTSIDE IT WILL EXECUTE WHILE CHECKADDRESS IS IN PROGRESS
});
Your submit function is also most likely running the default behavior, use preventDefault
jQuery("#submitOrder").submit(function(e){
e.preventDefault();
//code
});
On my map I have some Markers. Onclick I want to get the markers address using reserve geocoding.
Here is my function:
...
google.maps.event.addListener(marker_obj[ii], 'click', function(){
show_marker_information(this);
});
...
function show_marker_information(obj){
//obj = marker
if(typeof(infowindow) != 'undefined')
infowindow.close();
var latlng_search = obj.getPosition();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latlng': latlng_search
},
function(results, status){
alert(results.toSource());
}
);
When clicking on a marker firebug tells me:
Unknown property <latlng>
[Break On This Error] J.toSpan=function(){return new P(this....n(d){return d==k&&c||d instanceof a}}
Any ideas?
I found my error:
geocoder.geocode({
'latlng': latlng_search
},
function(results, status){
alert(results.toSource());
}
);
there is no 'latlng' property at geocoder. it has to be 'location' instead of 'latlng'.