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;
});
Related
I am trying to pass the address information that comes from a database and showing in a textbox (txAddress from SQL) to another textbox (txInputAddress GMap). In order to pass the value from txAddress to txInputAddress I needed to use an updatepanel. Here is how I coded it:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div id="pac-container">
<asp:TextBox ID="txInputAddress" runat="server" placeholder="Enter a location" Width="415px" AutoPostBack="true" autocomplete="off"></asp:TextBox>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnCopytToGoogleMaps" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
This is the JavaScript I am using from Google, which I modified in order to use a C# textbox to make it easier to pass the value from one textbox to another, as mentioned before.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 35.6145169, lng: -88.81394690000002 },
zoom: 13
});
var card = document.getElementById('pac-card');
var input = document.getElementById("txInputAddress");
var types = document.getElementById('type-selector');
var strictBounds = document.getElementById('strict-bounds-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
radioButton.addEventListener('click', function () {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
document.getElementById('use-strict-bounds')
.addEventListener('click', function () {
console.log('Checkbox clicked! New state=' + this.checked);
autocomplete.setOptions({ strictBounds: this.checked });
});
}
Here is an image of what I get. As you can see, it shows the address from txAddress to txInputAddress but then if you don't refresh the page, the autocomplete will not show up. Any idea what to do to solve this issue? In other words, I need to pass the address from txAddress to txInputAddress and show the autocomplete options.
After using the UpdatePanel, the browser has lost the controls and elements in the DOM. They have to be rebinded. So use the function below to call initMap every time the UpdatePanel is triggered.
<script type="text/javascript">
initMap();
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
initMap();
});
</script>
How to get place ids from address_components using google api for web? Is it possible to get the id of the titles?
$(document).ready(function() {
$(document).on('change', '#s', function () {
window.setTimeout(function () {
googleMapsLoaded(); }, 300);
});
});
var autocomplete; function initialize() {
var options = {
types : ['(regions)'] };
var input = document.getElementById('s');
autocomplete = new google.maps.places.Autocomplete(input , options, googleMapsLoaded);
}
var map = google.maps.event.addDomListener(window, 'load', initialize);
function googleMapsLoaded(){
var place = autocomplete.getPlace();
console.log(place.place_id);
}
My code
html:
input type='text' name='Address_A' id='Address_1' placeholder='Nhập địa chỉ' autocomplete='off'
javascript:
var input = document.getElementById("Address_1");
var autocomplete = new google.maps.places.Autocomplete(input, { types:['geocode'] });
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
input.value = name;
});
but textbox is not show incorrect. Something wrong?
You can try on Google API doc
The link is here with demo
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete
Cheers :D
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
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