Reputation: 241
I cannot get my geocoding to work in one of my jsp pages. It's working in another but this one is causing trouble.
I have a base.jsp which is shared among all my jsp pages. which has:
var geocoder;
$(document).ready(function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center : { lat : 56.138, lng : 8.967 },
zoom : 7,
disableDoubleClickZoom : true
});
geocoder = new google.maps.Geocoder();
});
function addressTolatlng(address){
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();
var myLatlng = new google.maps.LatLng(latitude, longitude);
console.log(myLatlng);
}
});
}
This is my jsp page which gives the error:
$( document ).ready(function() {
console.log(input);
var input = document.getElementById('addressField');
var autocomplete = new google.maps.places.Autocomplete(input, {
types: ["geocode"]
});
autocomplete.bindTo('bounds', map);
});
<input type="text" placeholder="address" name="address" id="addressField" class="form-control" aria-label="..." value="">
<script>
$("#addressField").keyup(function() {
var address = document.getElementById('addressField').value;
addressTolatlng(address);
});
</script>
I get Uncaught TypeError: Cannot read property 'geocode' of undefined when running this. But I got another page which has the same setup, and there it works perfectly, so its kind odd for me how this one won't behave the same way.
the console also gives these:
(anonymous function) @ eventHandler?action=createEvent:790
m.event.dispatch @ jquery-1.11.3.min.js:4
r.handle @ jquery-1.11.3.min.js:4
I have alot of script imports, which for me is the only difference on the pages. Can this cause the problem?
Upvotes: 0
Views: 4457
Reputation: 1238
In this line of code
geocoder.geocode( { 'address': address}, function(results, status) {
geocoder is undefined (or null) and nothing can be accessed in it b/c it doesn't know what geocoder is.
The reason it is undefined is that geocoder is outside the scope of your addressTolatlng function. To fix this you can a) pass in geocoder to your function through a parameter b) define geocoder again in that function or c) add the function to your iniatilize() function (but I'm not 100% on that one)
Hope that helps!
Upvotes: 3