问候。
我正在尝试修改Shawn Mayzes JQuery Google Maps插件,以支持检索“当前”的latlng属性。
Shawn的插件和示例可以在这里找到:http://www.mayzes.org/googlemaps.jquery.examples.html
我关注的例子是“Map Geocoding Simple”(http://www.mayzes.org/fragments/new/geocode.html)。插件中的相关功能是:
if ( opts.geocode ) {
geocoder = new GClientGeocoder();
geocoder.getLatLng(opts.geocode, function(center) {
if (!center) {
alert(address + " not found");
}
else {
$.googleMaps.gMap.setCenter(center, opts.depth);
$.googleMaps.latitude = center.x;
$.googleMaps.longitude = center.y;
}
});
}
else {
// Latitude & Longitude Center Point
var center = $.googleMaps.mapLatLong(opts.latitude, opts.longitude);
// Set the center of the Map with the new Center Point and Depth
$.googleMaps.gMap.setCenter(center, opts.depth);
}
现在,我想要做的是在将广告地址传递给插件后,检索“中心点”,即中心点的纬度/经度值。
所以,在我传递地址的代码中,因此:
$('#map').googleMaps({
geocode: add
});
我想要一些像这样检索lat / long的方法:
$('#map').getLatLng();
...或作为插件实例化中的回调函数(就像他们在JQuery UI Tabs控件中所做的那样)。
那些将是“理想”的解决方案,但与此同时,我愿意用黑客“满足自己”。为什么不使用像这样的Jquery“数据”函数?
if ( opts.geocode ) {
geocoder = new GClientGeocoder();
geocoder.getLatLng(opts.geocode, function(center) {
if (!center) {
alert(address + " not found");
}
else {
alert('center--'+center);
**$(this).data('latlng', center);**
$.googleMaps.gMap.setCenter(center, opts.depth);
$.googleMaps.latitude = center.x;
$.googleMaps.longitude = center.y;
}
});
}
else {
// Latitude & Longitude Center Point
var center = $.googleMaps.mapLatLong(opts.latitude, opts.longitude);
// Set the center of the Map with the new Center Point and Depth
$.googleMaps.gMap.setCenter(center, opts.depth);
}
然后我就可以通过简单地引用来检索latlng值:
$('#map').data('latlng');
但是,唉,这根本不起作用。
对类似问题的任何指导/提示/解决方案都将提供很大帮助。
无耻
/////////////////////////////////////////////// ///////// 对Matchu的回应 ////////////////////////////////////////////////// //////
谢谢你的想法。这是我试过的:
$.googleMaps = {
mapsConfiguration: function(opts) {
var ThisMap = this;
// GEOCODE
if ( opts.geocode ) {
geocoder = new GClientGeocoder();
geocoder.getLatLng(opts.geocode, function(center) {
if (!center) {
alert(address + " not found");
}
else {
alert('center--'+center);
ThisMap.data('latlng', center);
$.googleMaps.gMap.setCenter(center, opts.depth);...
“var ThisMap = this”在插件的第3行,对我来说似乎很“高”:)
我尝试使用以下方法检索“latlng”:
var map = $('#map').googleMaps({
geocode: add
});
alert('latlng--'+map.data('latlng'));
我知道这里需要发生的事情是可能的,因为我在其他插件中使用过类似的用法。不幸的是,这些插件看起来非常“高级”,我还没有看到在任何简单的JQuery插件教程中存储和检索当前属性值的示例。还有其他人吗?
答案 0 :(得分:0)
我的第一个猜测是this
不再引用该元素。在没有看到整个代码的情况下,我的猜测是this
在该片段的第3行开始的匿名函数内重置。尝试将其存储到上面的变量:
if ( opts.geocode ) {
geocoder = new GClientGeocoder();
var element = this; // really you should move the var declaration up higher
geocoder.getLatLng(opts.geocode, function(center) {
// ...
});
}
当然,即使在那里,$(this)
仍然可以引用别的东西,因为我还没有完成整个插件。如果您不确定,请尝试记录(alert,console.log,等等)this
中存储的内容。