I’m trying to implement Google Places API, so here is my code:
JavaScript
x
27
27
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
5
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&location=0,0&radius=20000000&language=de"></script>
6
<script>
7
$(document).ready(function() {
8
var el = $('#street').attr("placeholder", "")
9
, autocomplete = new google.maps.places.Autocomplete( ( el.get(0) ), { types: ['geocode'] } );
10
11
el.bind("blur", function() {
12
// blur is triggered before place_changed, as well as focus... so this is not working as well
13
})
14
15
google.maps.event.addListener(autocomplete, 'place_changed', function() {
16
var place = autocomplete.getPlace();
17
18
el.val(place.name); // this line is not working well - still default content showing !!!
19
});
20
})
21
</script>
22
</head>
23
<body">
24
<input type="text" id="street" style="width:400px;" />
25
</body>
26
</html>
27
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/
Advertisement
Answer
I was able to solve my problem with the following code:
JavaScript
1
21
21
1
$(document).ready(function() {
2
var el = $('#street').attr("placeholder", "")
3
, autocomplete = new google.maps.places.Autocomplete( ( el.get(0) ), { types: ['geocode'] } );
4
5
el.bind("blur", function() {
6
el.css("color", "#fff"); // this will prevent text flashing
7
})
8
9
google.maps.event.addListener(autocomplete, 'place_changed', function() {
10
var place = autocomplete.getPlace();
11
12
el.val(place.name);
13
14
// this will override default Google suggestion
15
setTimeout(function() {
16
el.val(place.name);
17
el.css("color", "");
18
}, 0)
19
});
20
})
21