我创建了谷歌地图,并为一些有名称和地址的餐馆提供标记。标记正在从mysql数据库中获取。
我正在尝试在标记上放置名称后面的餐馆的URL链接,这样如果您点击标记,它将打开浏览器到他们的网站。
这是地图的html代码:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(51.8980, -8.4737),
zoom: 16
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl('locator.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
我尝试将一个链接变量添加到数据库中,并使用此代码将其显示在标记上,但它不起作用。无论如何我能做到吗?
答案 0 :(得分:1)
我假设您在AJAX请求的响应中获得了url
值。只需将其作为属性添加到每个标记,并修改click事件处理程序以重定向到该URL:
downloadUrl('locator.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label,
url: markerElem.getAttribute('url');
});
marker.addListener('click', function() {
window.location.href = this.url;
});
});
});
答案 1 :(得分:0)
我也看不到你在哪里获得infowindow的网址。请尝试:
var url = putYourUrlHereSomehow;
var urlLink = document.createElement("a");
urlLink.setAttribute('href', url);
var t = document.createTextNode(url);
urlLink.appendChild(t);
infowincontent.appendChild(urlLink);
这会创建一个可点击的链接并将其设置为:
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});