我有这个函数,它在标记被放入地图后获取标记的坐标:
$(function() {
$( "#add-marker" ).draggable({
containment: "map",
helper: "clone",
start: function(evt, ui) {
$('#navbar').fadeTo('fast', 0.6, function() {});
},
stop: function(evt, ui) {
// Turning coordinates into a string and then removing unwanted characters
var string = String(map.containerPointToLatLng([ui.offset.left, ui.offset.top]));
string = string.replace('LatLng(', '');
string = string.replace(' ', '');
string = string.replace(')', '');
console.log(typeof string); // ---> Shows my coordinates
addProperty(string);
}
});
});
问题是,当我传递“string”时,它会被转换为一个对象:
function addProperty(coords){
$.magnificPopup.open({
tLoading:"Loading...",
modal:false,
showCloseBtn: true,
closeBtnInside: true,
type:'inline',
alignTop:false,
items:{src: $('#test-popup')},
callbacks: {
open: function(coords) {
console.log(typeof $(this).data(coords)); // ---> Shows object
$('#coords').val($(this).data(coords));
}
}
});
}
如何将“string”传递给addProperty函数并仍将其作为字符串?
答案 0 :(得分:3)
在第二个示例中,您处理来自coords
回调的open
值,而不是来自高级函数addProperty
的值。
要解决此问题,只需从coords
回调中重命名open
变量名称:
function addProperty(coords) {
$.magnificPopup.open({
callbacks: {
open: function(newCoords) {
/*
Here, you can access coords wich is still the string version,
or newCoords wich is the new object returned by the callback.
*/
}
}
});
}
答案 1 :(得分:1)
如果您访问lat
返回的lng
对象的L.LatLng
和containerPointToLatLng
属性,您将会更加轻松:
stop: function(evt, ui) {
var ll = map.containerPointToLatLng([ui.offset.left, ui.offset.top]);
var str = '' + ll.lat.toFixed(4) + ',' + ll.lng.toFixed(4);
addProperty(str);
}