【发布时间】:2013-03-13 01:09:37
【问题描述】:
您好,我正在尝试在单击图形时让一些图钉显示在谷歌地图上。 我将我需要的所有数据存储在跨度标签上的数据位置元素中:
<span class="showOnMap" data-location="{"lat":"51.4894805","lng":"-0.2942533000000367","name":"Brentford Towers","addr":"Green Dragon Lane\r\nBrentford TW8 0DF","pinType":"loc"}"> <img width="32" height="32" src="/images/Icons/map-icon.png">
</span>
我的点击功能是:
$('.showOnMap').click(function(){
//alert('click');
var myData = $(this).data('location');
console.log(myData);
createMarkerWithInfo(myData);
//addToPanel(panelData);
})
创建标记的功能导致我出现问题,当我提醒它或尝试使用它来创建标记时,传递给它的数据显示为未定义,但它确实显示在控制台中,但从我'一直在读取控制台不应该被信任,因为它会以当前状态显示数据,即它可能在实际调用控制台时未定义,
我不明白为什么它的未定义为 json 数据在 dom 中(它实际上由 php 生成)所以在 dom 中定义,我可以理解如果我正在执行 Ajax 调用为什么它可能会出现未定义。
function createMarkerWithInfo(myData){
//console.log(myData);
//coords = myData.latlng.split(',');
alert(myData + 'pinType: '+ myData.pinType + ' lat: '+ myData.lat + ' lng: ' +myData.lng);
myLatLng = new google.maps.LatLng(myData.lat, myData.lng);
if(myData.pinType == 'loc'){
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: myData.name,
icon: locimage,
shadow: locshadow,
shape: locshape
});
}
if(myData.pinType == 'ub'){
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: myData.name,
icon: ubimage,
shadow: ubshadow,
shape: locshape
});
}
//alert('lat: '+myData.lat+','+'lng: '+myData.lng);
// Wrapping the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(myData, marker) {
// Creating the event listener. It now has access to the values of
// myData and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
//create thecontent for the infowindow
var content = createContent(myData);
infowindow.setContent(content);
infowindow.open(map, marker);
});
})(myData, marker);
markersArray.push(marker);
markersPosArray.push(myLatLng);
bounds.extend(myLatLng);
map.fitBounds(bounds);
zoomMarkers();
}
http://2012.reelfilmlocations.co.uk/Modules/builder_areaLocs.php 是我正在处理的页面,奇怪的是我有一个类似的页面(使用 php 包含而不是独立页面),它具有相同的功能并且可以工作,我查看了两者并且也看不出差异是什么导致它未定义) http://2012.reelfilmlocations.co.uk/locations-london-west/
【问题讨论】:
-
术语:您不会对 DOM 进行 Ajax 调用。 Ajax 是服务器/客户端通信。
-
来自 jquery .data() doc
Regarding HTML5 data-* attributes: This low-level method does NOT retrieve the data-* attributes unless the more convenient .data() method has already retrieved them.考虑使用 jquery.attr() -
当数据属性为对象(以'{'开头)或数组(以'['开头)时,使用jQuery.parseJSON解析字符串;它必须遵循有效的 JSON 语法,包括引用的属性名称。 data- 属性在第一次访问 data 属性时被拉取,然后不再被访问或改变(所有数据值都存储在 jQuery 内部)。
标签: jquery google-maps-api-3 undefined html5-data