2010-01-21 4 views
2

Следующий класс Mootools помогает разработчику нарисовать оверлей круга на Карте Google с помощью API Карт Google v3. Я использую jQuery в своих проектах и ​​знаниях начального уровня в объектно-ориентированном javascript.Преобразование класса из Mootools в jQuery или классический javascript

В API Google Maps v2 это очень просто, но API v3 в настоящее время не имеет встроенных методов рисования кругов на карте. Кроме того, в документации API есть some description, так как это можно сделать по-другому.

Я хочу использовать следующий метод CircleOverlay в своем проекте с jQuery или классическим Javascript.

Может ли кто-нибудь помочь преобразовать следующие строки Mootools в jQuery-совместимый или классический подход к javascript?

var CircleOverlay = new Class({ 
Implements: [Options], 
options: { 
    numPoints: 100, 
    drawOptions: { 
    strokeColor: "#FF0000", 
    strokeOpacity: 0.8, 
    strokeWeight: 2, 
    fillColor: "#FF0000", 
    fillOpacity: 0.35 
    } 
}, 

initialize: function(map, center, radius, options) { 
    this.setOptions(options); 

    google.maps.OverlayView.call(this);  
    var q = 180/63781370/Math.sin(90 - center.lat())/Math.PI; 

    this._map = map; 
    this._point = center; 
    this._radius = radius * q * 10; // convert meters to latlang degrees 

    // Fit bounds of a circle that is drawn into the map 
    var d2r = Math.PI/180; 
    this.circleLatLngs = new Array(); 
    var circleLat = this._radius; 
    var circleLng = circleLat/Math.cos(center.lat() * d2r); 

    this.latlngbounds = new google.maps.LatLngBounds(); 

    // 2PI = 360 degrees, +1 so that the end points meet 
    for (var i = 0; i < this.options.numPoints + 1; i++) { 
    var theta = Math.PI * (i/(this.options.numPoints/2)); 
    var vertexLat = center.lat() + (circleLat * Math.sin(theta)); 
    var vertexLng = parseFloat(center.lng()) + parseFloat((circleLng * Math.cos(theta))); 
    var vertextLatLng = new google.maps.LatLng(vertexLat, vertexLng); 
    this.circleLatLngs.push(vertextLatLng); 
    this.latlngbounds.extend(vertextLatLng); 
    } 
    map.fitBounds(this.latlngbounds); 
    this.setMap(map); 
}, 

onAdd: function() { 
    var polyOptions = this.options.drawOptions; 
    polyOptions.paths = this.circleLatLngs; 
    this.polygon = new google.maps.Polygon(polyOptions); 
    this.polygon.setMap(this.map); 
}, 

onRemove: function() { 
    this.polygon.setMap(null); 
}, 

draw: function() { 
    this.onRemove(); 
    this.onAdd(); 
} 
}); 
CircleOverlay.implement(new google.maps.OverlayView()); 

ответ

2

Я просто сделал что-то похожее на прошлые выходные.

Не проверял, но ...

var CircleOverlay = function(map, center, radius, options) { 
    this.options = { 
     // all options here, 
     // including an custom check to override the options, e.g.: 
     numPoints: options.numPoints || 100, 
     // etc... 
    }; 

    // everything from initialize here; 

    this.onAdd: function() { 
     var polyOptions = this.options.drawOptions; 
     polyOptions.paths = this.circleLatLngs; 
     this.polygon = new google.maps.Polygon(polyOptions); 
     this.polygon.setMap(this.map); 
    }; 

    this.onRemove: function() { 
     this.polygon.setMap(null); 
    }; 
    this.draw: function() { 
     this.onRemove(); 
     this.onAdd(); 
    }; 
}; 
+0

Очень спасибо за ваш быстрый ответ, но до сих пор не решена. Я добавил свои параметры, подобные вашим, чем я добавил весь блок инициализации до «this.onAdd: ...», и я заменил знаки «:» на «=» (eq this.onAdd: function() на this.onAdd = function() ..). Теперь я получаю сообщение об ошибке: «this.setMap() не является функцией» – edigu

+0

это из-за: 'CircleOverlay.implement (new google.maps.OverlayView());' - ваш класс реализует в нем еще один класс и наследует его методы. вам необходимо преобразовать оба ... –

+0

Димитар Кристофф прав. Также необходимо включить функции из 'google.maps.OverlayView'. – jerone

1

РЕШИТЬ! Спасибо Димитр & jerone.

Это может помочь любому в будущем. Окончательный рабочий код выглядит так:

var CircleOverlay = function(map, center, radius, options) { 
    this.options = { 
      numPoints: 50, 
      drawOptions: { 
       strokeColor: "#FF0000", 
       strokeOpacity: 0.8, 
       strokeWeight: 2, 
       fillColor: "#FF0000", 
       fillOpacity: 0.35 
      } 
     }; 
    // Extending with jQuery. So another ways possible 
    this.options = $.extend(this.options, options || {});  
    google.maps.OverlayView.call(this);     
    var q = 180/63781370/Math.sin(90 - center.lat())/Math.PI;  
    this._map = map; 
    this._point = center; 
    this._radius = radius * q * 10; // convert meters to latlang degrees 

    // Fit bounds of a circle that is drawn into the map 
    var d2r = Math.PI/180; 
    this.circleLatLngs = new Array(); 
    var circleLat = this._radius; 
    var circleLng = circleLat/Math.cos(center.lat() * d2r); 

    this.latlngbounds = new google.maps.LatLngBounds(); 

    // 2PI = 360 degrees, +1 so that the end points meet 
    for (var i = 0; i < this.options.numPoints + 1; i++) { 
     var theta = Math.PI * (i/(this.options.numPoints/2)); 
     var vertexLat = center.lat() + (circleLat * Math.sin(theta)); 
     var vertexLng = parseFloat(center.lng()) + parseFloat((circleLng * Math.cos(theta))); 
     var vertextLatLng = new google.maps.LatLng(vertexLat, vertexLng); 
     this.circleLatLngs.push(vertextLatLng); 
     this.latlngbounds.extend(vertextLatLng); 
    } 
    map.fitBounds(this.latlngbounds); 
    this.setMap(map); 

    this.onAdd = function() { 
     var polyOptions = this.options.drawOptions; 
     polyOptions.paths = this.circleLatLngs; 
     this.polygon = new google.maps.Polygon(polyOptions); 
     this.polygon.setMap(this.map); 
    };  

    this.onRemove = function() { 
     this.polygon.setMap(null); 
    }; 
    this.draw = function() { 
     this.onRemove(); 
     this.onAdd(); 
    }; 
}; 

Наконец

CircleOverlay.prototype = google.maps.OverlayView.prototype; 
Смежные вопросы