以下代码在页面上找到memberId并渲染地图并成功放置标记,但不是将地图置于标记的中心。地图最终集中在可能是默认位置(索马里)。
我做错了什么?
function initialize() {
var memberId = $('#member-section').data("member-id");
if (typeof memberId === "undefined") {
memberId = 0;
}
var latitude = $('#member-section').data("latitude");
if (typeof latitude === "undefined") {
latitude = 51.21921589999999;
}
var longitude = $('#member-section').data("longitude");
if (typeof longitude === "undefined") {
longitude = 4.402881799999932;
}
var mapCentreLatlng;
mapCentreLatlng = new google.maps.LatLng(latitude, longitude);
buildMap(memberId, mapCentreLatlng);
}
function buildMap(memberId, mapCentreLatlng) {
google.maps.visualRefresh = true;
var infowindow = null;
var mapOptions = {
zoom: 5,
center: mapCentreLatlng,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create a custom marker
var markerImage = '/img/map-flag-alt.png';
// Get json data and loop to create markers for map
$.getJSON("/Umbraco/Api/searchmembers/GetMembers?memberId=" + memberId, function (data) {
$.each(data, function (members, member) {
// Add marker
var marker;
var memLatLng = new google.maps.LatLng(member.Latitude, member.Longitude);
marker = new google.maps.Marker({
position: memLatLng,
map: map,
title: member.MemberName,
icon: markerImage
});
// Add click event for marker
google.maps.event.addListener(marker, 'click', function () {
if (infowindow) {
infowindow.close();
}
// Create info window and create content
var contentString =
'<h2 id="firstHeading">' + member.MemberName + '</h2>' +
'<div id="bodyContent">' +
'<p>' + member.Address + '</p>' +
'<p><a href="' + member.Url + '">View Company Profile</a></p>' +
'</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, marker);
});
});
});
}
答案 0 :(得分:0)
也许在文档加载完成之前调用了function initialize()
,因此您的vars定义找不到#member-section
。
尝试在DOM完全加载$(document).ready(function initialize(){...});
时调用该函数,或者根据Titus注释添加map.setCenter(memLatLng)
以重新定位地图。