Reputation: 987
I have a problem including the Google Places API. I've set up everything with API key, the listing / suggestion works good but the place_changed
event do not get fired when i select an suggestion.
Check the Fiddle: https://jsfiddle.net/xj2d77be/3/
It should work, but i have absolutely no idea why it does not.
code snippet (from posted fiddle):
$(document).ready(function() {
var autocomplete = new google.maps.places.SearchBox(document.getElementById('mapLocation'));
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
console.log(place);
});
console.log("Initialized")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.google.com/maps/api/js?libraries=places"></script>
<input type="text" id="mapLocation" />
Upvotes: 2
Views: 6017
Reputation: 161384
There is no "place_changed" event or .getPlace()
function for SearchBox. It should be "places_changed" and .getPlaces()
.
Methods
getPlaces() Return Value: Array
Returns the query selected by the user, or null if no places have been found yet, to be used with places_changed event.
Events
places_changed Arguments: None
This event is fired when the user selects a query, getPlaces should be used to get new places.
Note: the .getPlaces()
function returns an array rather than a single place.
$(document).ready(function() {
var autocomplete = new google.maps.places.SearchBox(document.getElementById('mapLocation'));
google.maps.event.addListener(autocomplete, 'places_changed', function() {
var place = autocomplete.getPlaces();
console.log(place);
});
console.log("Initialized")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.google.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="text" id="mapLocation" />
Upvotes: 0
Reputation: 3848
For me, the place_changed
event would fire until I refreshed the page, then it would not fire anymore (using Google Chrome on a local webpage). You have to restart Chrome or close the developer tools and refresh the page for the event to fire again.
Upvotes: 0
Reputation: 320
try this, this will work i have updated your code,
https://jsfiddle.net/xj2d77be/4/
$(document).ready(function() {
var autocomplete = new google.maps.places.Autocomplete($("#mapLocation")[0]);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
console.log(place);
});
console.log("Initialized")
});
using SearchBox:
https://jsfiddle.net/xj2d77be/5/
$(document).ready(function() {
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapLocation'));
searchBox.addListener('places_changed', function() {
var place = searchBox.getPlaces();
console.log(place);
});
console.log("Initialized")
});
Upvotes: 2