Hi,
I am having a few problems with a javascript class that I need (want) for an application.
The code here is version 4 or 5 or something. I have tried creating a class with prototypes, with the dynamic prototype method, using the constructor, etc. But none of them worked properly.
The problem I am having is as follows:
I set the var this.divId of the object to a value, in this case ‘guide_map’. This is the id of the div that the google maps api will use to put the map into. But in the function ‘renderMap’ when I call this.divId it says it is undefined. But when I alert mymap.divId it shows up like it should.
When I do console.log(this) it shows Window 1, which would mean, I think, JS is not (yet) my language, that ‘this’ does not refer to the object, but to the whole window.
How do I fix this?
The code:
function renderMap(){
var options = {zoom: this.defaultZoom, center: this.divId, mapTypeId: google.maps.MapTypeId.ROADMAP};
this.map = new google.maps.Map(document.getElementById(this.divId), options);
}
function setDefaultLatLng(value, isaddress){
if (isaddress == null){
isaddress = false;
}
if(isaddress){
address = value;
this.geocoder.geocode({address:address}, this.handleSetDefaultLatLngAddress);
}
else{
//Value = object: {lat:12.12, lng: 12.12}
this.defaultLatLng = new google.maps.LatLng(value.lat, value.lng);
}
}
function setDefaultZoom(iZoom){
this.defaultZoom = iZoom;
}
function handleSetDefaultLatLngAddress(results, status){
if(status == google.maps.GeocoderStatus.OK){
//this.map.panTo(results[0].geometry.location);
//this.defaultLatLng = new google.maps.LatLng(results[0].geometry.location.a, results[0].geometry.location.b);
this.defaultLatLng = new google.maps.LatLng(results[0].geometry.location.a, results[0].geometry.location.b);
this.renderMap();
}
}
function setDivId(containerId){
this.divId = containerId;
}
function dcMap(){
//this.defaultLatLng;
this.defaultZoom = 12;
//The geocoder
this.geocoder = new google.maps.Geocoder();
//Attach the functions
this.setDivId = setDivId;
this.renderMap = renderMap;
this.setDefaultZoom = setDefaultZoom;
this.setDefaultLatLng = setDefaultLatLng;
this.handleSetDefaultLatLngAddress = handleSetDefaultLatLngAddress;
};
var mymap = new dcMap();
mymap.setDivId('guide_map');
mymap.setDefaultZoom(13);
mymap.setDefaultLatLng('Amsterdam, Netherlands', true);