Reputation: 1695
I'm trying to implement Google Places API, so here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&location=0,0&radius=20000000&language=de"></script>
<script>
$(document).ready(function() {
var el = $('#street').attr("placeholder", "")
, autocomplete = new google.maps.places.Autocomplete( ( el.get(0) ), { types: ['geocode'] } );
el.bind("blur", function() {
// blur is triggered before place_changed, as well as focus... so this is not working as well
})
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
el.val(place.name); // this line is not working well - still default content showing !!!
});
})
</script>
</head>
<body">
<input type="text" id="street" style="width:400px;" />
</body>
</html>
Google Autocomplete works fine, however I have one of requirements - only show street name & number instead of full address suggested by Google. So I can get all information by running autocomplete.getPlace()
at "place_changed" event - there are no problems with that.
The problem is that I can't override autocomplete input value with my custom text - I've tried to do it within "blur", "focus", "place_changed" events - still no luck. Please find an example of what I was trying. Also - I need to avoid text flashing, to make it absolutely user-friendly. Could someone help me with my attempts?
JSFiddle: http://jsfiddle.net/8pGH2/
Upvotes: 4
Views: 5276
Reputation: 1695
I was able to solve my problem with the following code:
$(document).ready(function() {
var el = $('#street').attr("placeholder", "")
, autocomplete = new google.maps.places.Autocomplete( ( el.get(0) ), { types: ['geocode'] } );
el.bind("blur", function() {
el.css("color", "#fff"); // this will prevent text flashing
})
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
el.val(place.name);
// this will override default Google suggestion
setTimeout(function() {
el.val(place.name);
el.css("color", "");
}, 0)
});
})
Upvotes: 1