2012-07-10 131 views
0

我正在使用JavaScript的自定义对象为小个人项目主要用于平板电脑(但与笔记本电脑以及)。该对象处理谷歌地图,GPS跟踪以及其他程序。在对象内部,我定义了从对象外部调用的函数(enableGps, disableGps)。在enableGps里面,我开始使用外部error_handler和内部对象函数(this.handleGps)来处理GPS数据(纬度,经度,精度等)。在this.handleGps我尝试拨打this.updateGpsMarker函数来更新地图上的实际标记,但引发异常。如何从同一对象中的不同函数调用对象定义的函数?

Uncaught TypeError: Object [object Window] has no method 'updateGpsMarker'

我如何可以调用从this.handleGpsthis.updateGpsMarker?请注意我需要this.updateGpsMarker作为一个函数从外部调用(长解释) 我会抛出代码,以使它更清楚我正在尝试做什么。

function RouteAssistant(mapCanvas, mapOptions) 
{ 
    // Google mapping and geocoding 
    this.map = new google.maps.Map(mapCanvas, mapOptions); 
    this.geo = new google.maps.Geocoder(); 
    this.gpsMarker = null; 

    this.updateGpsMarker = function(lat, lon) 
    { 
     console.log("Updating GPS marker"); 
     if (this.gpsMarker == null) 
     { 
      console.log("GPS Marker not created. Creating GPS marker at " + lat + "," + lon); 
      this.gpsMarker = new google.maps.Marker(
      { 
       position: new google.maps.LatLng(lat,lon), 
       map: this.map, 
       title: "I am here!" 
      }); 
      this.map.setCenter(new google.maps.LatLng(lat,lon)); 
     } 
     else 
     { 
      console.log("GPS Marker created. Updating GPS marker to " + lat + "," + lon); 
      this.gpsMarker.setPosition(new google.maps.LatLng(lat,lon)); 
     } 
    } 

    // GPS and tracking 
    this.gpsProcess = null; 
    this.enableGps = function (handle_errors) 
    { 
     if (this.gpsProcess == null) { 
      console.log("Enabling GPS"); 
      this.gpsProcess = navigator.geolocation.watchPosition(this.handleGps, handle_errors); 
     } 
    }; 
    this.disableGps = function() 
    { 
     if (this.gpsProcess != null) 
     { 
      console.log("Disabling GPS"); 
      navigator.geolocation.clearWatch(this.gpsProcess); 
      this.gpsProcess = null; 
     } 
    }; 
    this.handleGps = function(position) 
    { 
     this.updateGpsMarker(position.coords.latitude, position.coords.longitude); 
    } 
} 
+0

使用只有这样,我才能完成这项工作是通过定义外部(对象外)updateGpsMarker函数并将RouteAssistant对象传递给它。这是我最后的手段 – 2012-07-10 00:49:39

+0

你究竟是怎么调用updateMarker函数的? – vishakvkt 2012-07-10 01:09:36

回答

0

也许你可以使用类似的启迪模模式创建一个干净的对象,并把所有的功能于他,像这样

var routeAssistant = function(mapCanvas, mapOptions) { 

    var map = new google.maps.Map(mapCanvas, mapOptions). 
    updateGpsMarker = function(lat, long) { 
     //You can directly access 'map' here. 
    }; 
    return { 
     updateGpsMarker : updateGpsMarker 
    }; 
}; 

然后,您可以通过执行

var myObject = new routeAssistant(mapCanvas, mapOptions); 
    myObject.updateGpsMarker(latitude,longtitude); 
相关问题