Geocode on autocomplete click - javascript

This is the code I am working from:
http://jsfiddle.net/njDvn/75/
var GeoCoded = {done: false};
$(document).ready(function(){
console.log('ready!');
autosuggest();
console.log($('#myform input[type="submit"]'));
$('#myform').on('submit',function(e){
if(GeoCoded.done)
return true;
e.preventDefault();
console.log('submit stopped');
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());
//if you only want to submit in the event of successful geocoding, you can only trigger submission here.
GeoCoded.done = true;
$('#myform').submit();
} else {
console.log("Geocode was not successful for the following reason: " + status);
//enable the submit button
$('#myform input[type="submit"]').attr('disabled',false);
}
});
});
});
This works how I want BUT, I wanted to complete the geocode when someone clicks on the autocomplete. So, when they type something and click on a suggestion from the autosuggest list, it actually completes the geocode call when the click the result.
If anyone could tell me if this is possible I would really appreciate it, because I havent been able to figure out how to do it myself.
​

Autocomplete incorporates geocoding automatically. Example here.
Edit:
Here is the gist of that example:
The key lines for creating the autocomplete control are:
var input = document.getElementById('searchTextField');
var options = {
types: [],
componentRestrictions: {country: 'us'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
You also need to load the Places library:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
and in your HTML:
<input id="searchTextField" type="text" size="50" value="">
By the way, you don't "add autocomplete to the geocoder".The Places Autocomplete class includes geocoding capabilities.

Related

Uncaught TypeError: Cannot read property 'geometry' of undefined

I have gotten google auto-complete to work, but just in case the user doesn't select the autocomplete, I am trying to submit the address to Google and retrieve the latitude and longitude myself.
The issue I am having is when I submit without using autocomplete I am getting Uncaught
TypeError:
Cannot read property 'geometry' of undefined and Uncaught
TypeError: Cannot read property 'location' of undefined (none of my
console.logs are triggered).
If I submit with autocomplete I still get Uncaught
TypeError: Cannot read property 'geometry' of undefined
even though the autocomplete did work to get the address with the lat and long.
My Html
<form method="GET" id="my-form" action="/search" onsubmit="check()">
<input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
<input id="latitude" type="hidden" name="latitude">
<input id="longitude" type="hidden" name="longitude">
</form>
I call geo() autocompleting, but in case they don't use the autocomplete, I try to catch it on submit with my check() function. Here is my JS
function check() {
let latitude = document.getElementById("latitude").value;
if (latitude) {
console.log(latitude);
} else {
let term = $("#getaddy").val();
$.ajax({
url: "https://maps.googleapis.com/maps/api/geocode/json?address="+encodeURIComponent(term) +"&key=GOOGLEKEY",
type: 'get',
success: function(data) {
if (data.status === 'OK') {
// Get the lat/lng from the response
let lat = data.results[0].geometry.location.lat;
let lng = data.results[0].geometry.location.lng;
console.log("pass");
}
},
error: function(msg) {
console.log("fail");
}
});
return true;
}
}
function geo() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('getaddy')), {
types: ['geocode']
});
autocomplete.addListener('place_changed', addlatlong);
}
function addlatlong() {
var place = autocomplete.getPlace();
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
document.getElementById("latitude").value = latitude;
document.getElementById("longitude").value = longitude;
}
Thank you so much for any help!
If you already have the two property values latitude and longitude, I suggest you to use this code (provided by Google) to get address (not using jquery ajax):
var geocoder = new google.maps.Geocoder;
var latlng = { lat: latitude, lng: longitude };
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
if (results[0]) {
var address = results[0].formatted_address);
console.log(address);
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
Source: Reverse Geocoding (Address Lookup)
If they don't submit the request, you can try to use jquery to caugh the event when the searchBox lost the focus (focusout), then calling event places_changed to get the latitude and the longitude.
Source: Places Search Box
Source: Trigger places_changed in Google maps from submit button

Does Google MAP API Use Async Request

I wrote a small app to test out Google Map API and I noticed that my functions do not execcute in the expected order. Please take a look at my code below.
<!DOCTYPE html><htm><head><title></title>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"> </script>
<script>
//Global Variables
var lat, lng, _Address;
var geocoder = new google.maps.Geocoder();
function getReverseGeocodingData(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
// Make the Geocode request
geocoder.geocode({ 'latLng': latlng }, function (searchResults,searchStatus) {
if (searchStatus !== google.maps.GeocoderStatus.OK) {
alert("Your search yields " + searchStatus);
}
// Checking to see if the Geocode Status is OK before proceeding
if (searchStatus == google.maps.GeocoderStatus.OK) {
console.log(searchResults);
_Address = (searchResults[0].formatted_address);
alert("First time Address is displayed" + _Address);
}
});
}
function splitAddress() {
var addressArr = _Address.split(',');
//addressArr will be used later
}
// This function is called when the submit button is clicked
function SearchAddress() {
geocoder.geocode({ 'address': "77 Massachusetts Ave, Cambridge, MA 02139" }, function (searchResults, searchStatus) {
var location = searchResults[0].geometry.location;
lat = location.lat();
lng = location.lng();
getReverseGeocodingData(lat, lng);
alert("Second time Address is displayed" + _Address);
splitAddress();
});}
</script></head><body><div><input type="button" value="Submit" onclick="SearchAddress()"></div></body></html>
When I set a break point on the line alert("First time Address is displayed" + _Address), I can tell that this alert function executes before the line alert("Second time Address is displayed" + _Address).
However, the line alert("Second time Address is displayed" + _Address) appears as though it executes first and the value of _Address is undefined. So my question is if the second alert function executes after the first alert function, is Google Map API making an asynchronous request.
Yes, Google Maps API uses asynchronous requests when you call geocoder.geocode.
This is in the documentation.
Accessing the Geocoding service is asynchronous, since the Google Maps
API needs to make a call to an external server.

Getting Latitude and Longitude from Google Places search api using Javascript

How do I get the longitude and latitude from the searched location with the google maps place search box api.
Im using the same code as the google demo - https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
function GetLatlong() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('textboxid').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
});
}
You can use the above function which will give you the latitude and longitude for the area entered by user.
The code on the link you provide shows a function to do when a search is entered. First, it creates an empty array of markers (the pins you see on the map once you perform a search).
So, check the function starting with:
google.maps.event.addListener(searchBox, 'places_changed', function() {
You'll see later on that a marker has been created (there's even a comment):
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
So, on place.geometry.location you have a Google Maps Location object. You could use place.geometry.location.lat() and place.geometry.location.lng().
Check here, too: https://stackoverflow.com/a/15315483/1012139
From the docs:
// Autocomplete Options
var defaultBounds = new google.maps.LatLngBounds();
var options = {
types: ['(cities)'],
bounds: defaultBounds
};
// get DOM's input element
var input = document.getElementById('location_address');
// Make Autocomplete instance
var autocomplete = new google.maps.places.Autocomplete(input, options);
// Listener for whenever input value changes
autocomplete.addListener('place_changed', function() {
// Get place info
var place = autocomplete.getPlace();
// Do whatever with the value!
console.log(place.geometry.location.lat());
});
HTML:
<input type="text" id="address" name="address" value=""> //Autocomplete input address
<input type="hidden" name="s_latitude" id="s_latitude" value="" /> //get latitude
<input type="hidden" name="s_longitude" id="s_longitude" value="" /> //get longitude
Javascript:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
async defer></script>
<script>
var input = document.getElementById('address');
var originLatitude = document.getElementById('s_latitude');
var originLongitude = document.getElementById('s_longitude');
var originAutocomplete = new google.maps.places.Autocomplete(input);
originAutocomplete.addListener('place_changed', function(event) {
var place = originAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
originLatitude.value = place.geometry.location.lat();
originLongitude.value = place.geometry.location.lng();
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
originLatitude.value = results[0].geometry.location.lat();
originLongitude.value = results[0].geometry.location.lng();
}
});
}
});
</script>
navigator.geolocation.getCurrentPosition(success => {
console.log(success) // `have the lat and long`
}, failure =>{
//`enter code here if failed`
});

Jquery - Form not being submitted

I have some code which, when the search box is clicked, geocodes a location (unless laready done by the autosuggest) in the location box and should the submit the form.
The problem is, the form does not get submitted after the searhc button is clicked and the geocode is successful. Can anyone tell me where I am going wrong?
This is a link to the jsfiddle: http://jsfiddle.net/sR4GR/35/
This is the full code:
$(function () {
var input = $("#loc"),
lat = $("#lat"),
lng = $("#lng"),
lastQuery = null,
autocomplete;
function processLocation(query) {
var query = $.trim(input.val()),
geocoder;
if (!query || query == lastQuery) {
console.log("Empty or same variable");
return;
}
lastQuery = query;
geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: query
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
lat.val(results[0].geometry.location.lat());
lng.val(results[0].geometry.location.lng());
} else {
alert("We couldn't find this location. Please try an alternative");
}
});
}
autocomplete = new google.maps.places.Autocomplete(input[0], {
types: ["geocode"],
componentRestrictions: {
country: "uk"
}
});
google.maps.event.addListener(autocomplete, 'place_changed', processLocation);
$('#searchform').on('submit', function (event) {
processLocation();
event.preventDefault();
});
});
I don't know what processLocation(query) expects for query, but idea would be this:
1. change function signature
function processLocation(query, doSubmit) { // <--- new parameter
var query = $.trim(input.val()),
geocoder;
if (!query || query == lastQuery) {
console.log("Empty or same variable");
return;
}
lastQuery = query;
geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: query
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
lat.val(results[0].geometry.location.lat());
lng.val(results[0].geometry.location.lng());
if (doSubmit){
$('#searchform').submit(); //<-- new param usage
}
} else {
alert("We couldn't find this location. Please try an alternative");
}
});
}
2. remove this call
$('#searchform').on('submit', function (event) {
alert('Submitted')
event.preventDefault();
});
3. add this call
$('#search').click(function(){
processLocation(new Date(), true); //<-- don't know what's the first param
});
Tried to play around in your jsfiddle but had no success as I was constantly getting Empty or same variable message into console. I think you know your logic better and you'll figure out
I would just have the submit button disabled until the values are valid?
<input type="submit" value="Search" id="search" disabled="disabled">
search.removeAttr('disabled')
http://jsfiddle.net/sR4GR/38/
?

Google Maps Geocoder not giving results

I am using jQuery with the Google Maps API V3's Geocoder. The site user enters a location in the textbox and clicks on the submit button, which calls the code below to geocode the address given by the user into LatLng coordinates.
$(function(){
$("#searchbox_form #search_button").click(function(){
var address = $("#location").val();
var geocoder = new google.maps.Geocoder();
alert(address);
geocoder.geocode( { 'address': address}, function(results, status) {
alert("123");
if (status == google.maps.GeocoderStatus.OK) {
$("#user_lat").val(results[0].geometry.location.lat);
$("#user_lng").val(results[0].geometry.location.lng);
alert("lat: " + $("#user_lat").val());
alert("lng: " + $("#user_lat").val());
} else {
alert("asdasdasd");
alert(status);
}
});
});
});
However there is some problem. You will notice I placed several alert()s in the code. When 'Boston' is entered into the textbox and the submit button is clicked, only alert("address"); is executed showing Boston but alert("123") does not run. Did something go wrong somewhere?
Solution is to disable the submitting of the form :)
Check in any web - debugger whether any request is even made or not?
The code seems fine to me.

Categories

Resources