Javascript 单击标记时如何在Google地图中添加弹出窗口
我正在尝试使用jQuery JSON和PHP构建动态Google地图,这是我如何使用以下代码示例完成地图列表的一些方法:Javascript 单击标记时如何在Google地图中添加弹出窗口,javascript,php,jquery,json,google-maps,Javascript,Php,Jquery,Json,Google Maps,我正在尝试使用jQuery JSON和PHP构建动态Google地图,这是我如何使用以下代码示例完成地图列表的一些方法: <script type="text/javascript"> // Root path to data directory var dataRoot = 'gmap-master/'; // data file with markers (could also be a PHP file for dynam
<script type="text/javascript">
// Root path to data directory
var dataRoot = 'gmap-master/';
// data file with markers (could also be a PHP file for dynamic markers)
var newDate = new Date;
var markerFile = dataRoot + 'ammap.php';
// set default map properties
var defaultLatlng = new google.maps.LatLng(49.00, 10.00);
// zoom level of the map
var defaultZoom = 2;
var ndefaultZoom = 2;
// variable for map
var map;
// variable for marker info window
var infowindow;
// List with all marker to check if exist
var markerList = {};
// set error handler for jQuery AJAX requests
$.ajaxSetup({"error": function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' / ' + errorThrown + ' / ' + XMLHttpRequest.responseText);
}});
// option for google map object
var myOptions = {
zoom: defaultZoom,
center: defaultLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
/**
* Load Map
*/
function loadMap() {
console.log('loadMap');
// create new map make sure a DIV with id myMap exist on page
map = new google.maps.Map(document.getElementById("myMap"), myOptions);
// create new info window for marker detail pop-up
infowindow = new google.maps.InfoWindow();
// load markers
loadMarkers();
}
/**
* Load markers via ajax request from server
*/
function loadMarkers() {
// load marker jSon data
$.getJSON(markerFile, function(data) {
// loop all the markers
$.each(data.markers, function(i, item) {
// add marker to map
loadMarker(item);
});
});
}
/**
* Load marker to map
*/
function loadMarker(markerData)
{
// get date
var mDate = new Date(markerData['created'] * 1000);
// create new marker location
var myLatlng = new google.maps.LatLng(markerData['lat'], markerData['long']);
// create new marker
var marker = new google.maps.Marker({
id: markerData['id'],
map: map,
title: markerData['creator'] + ' - ' + markerData['name'],
position: myLatlng
});
// add marker to list used later to get content and additional marker information
markerList[marker.id] = marker;
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">"'.markerData['name'].'"</h1>'+
'<div id="bodyContent">'+
'<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
'sandstone rock formation in the southern part of the '+
'Northern Territory, central Australia. It lies 335 km (208 mi) '+
'south west of the nearest large town, Alice Springs; 450 km '+
'(280 mi) by road. Kata Tjuta and Uluru are the two major '+
'features of the Uluru - Kata Tjuta National Park. Uluru is '+
'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
'Aboriginal people of the area. It has many springs, waterholes, '+
'rock caves and ancient paintings. Uluru is listed as a World '+
'Heritage Site.</p>'+
'<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
'(last visited June 22, 2009).</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content:contentString
});
// add event listener when marker is clicked
// currently the marker data contain a dataurl field this can of course be done different
google.maps.event.addListener(marker, 'click', function() {
// show marker when clicked
infowindow.open(map,marker);
map.setZoom(6);
map.setCenter(marker.getPosition());
});
// add event when marker window is closed to reset map location
google.maps.event.addListener(infowindow, 'closeclick', function() {
});
// add marker to list
var listItem = $("<li/>");
$("<a/>").attr('href', '#').click(function() {
showMarker(marker.id);
return false;
}).text(markerData['name']).appendTo(listItem);
$('#myMapList').prepend(listItem);
}
/**
* Show marker info window
*/
function showMarker(markerId) {
// get marker information from marker list
var marker = markerList[markerId];
// check if marker was found
if (marker) {
// get marker detail information from server
$.get(dataRoot + 'data/' + 'markernew' + '.html', function(data) {
// show marker window
infowindow.setContent(data);
map.setZoom(6);
infowindow.open(map, marker);
});
} else {
alert('Error marker not found: ' + markerId);
}
}
/**
* Adds new marker to list
*/
function newMarker() {
// get new city name
var markerAddress = $('#newMarker').val();
if (markerAddress == "") {
$('#newMarker').addClass('error');
$('#newMarker').attr('placeholder', 'missing location');
return false;
}
// create new geocoder for dynamic map lookup
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': markerAddress}, function(results, status) {
// check response status
if (status == google.maps.GeocoderStatus.OK) {
// set new maker id via timestamp
var newDate = new Date;
var markerId = newDate.getTime();
// get name of creator
var markerCreator = prompt("Please enter your name", "");
// create new marker data object
var markerData = {
'id': markerId,
'lat': results[0].geometry.location.lat(),
'long': results[0].geometry.location.lng(),
'creator': markerCreator,
'name': markerAddress,
};
// save new marker request to server
$.ajax({
type: 'POST',
url: dataRoot + "data.php",
data: {
marker: markerData
},
dataType: 'json',
async: false,
success: function(result) {
// add marker to map
loadMarker(result);
// show marker detail
showMarker(result['id']);
$('#newMarker').removeClass('error');
// Track Piwik Goal
_paq.push(['trackGoal', 2]);
}
});
} else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
alert("Marker not found:" + status);
}
});
}
</script>
//数据目录的根路径
var dataRoot='gmap master/';
//带有标记的数据文件(也可以是用于动态标记的PHP文件)
var newDate=新日期;
var markerFile=dataRoot+'ammap.php';
//设置默认贴图属性
var defaultLatlng=新的google.maps.LatLng(49.00,10.00);
//地图的缩放级别
var=2;
var=2;
//映射变量
var映射;
//标记信息窗口的变量
var信息窗口;
//列出所有标记以检查是否存在
var-markerList={};
//为jQuery AJAX请求设置错误处理程序
$.ajaxSetup({“error”:函数(XMLHttpRequest、textStatus、errorshown){
警报(textStatus+'/'+ErrorSprown+'/'+XMLHttpRequest.responseText);
}});
//谷歌地图对象选项
变量myOptions={
缩放:默认缩放,
中心:DefaultLatling,
mapTypeId:google.maps.mapTypeId.HYBRID
};
/**
*负荷图
*/
函数loadMap(){
log('loadMap');
//创建新映射确保第页上存在id为myMap的DIV
map=new google.maps.map(document.getElementById(“myMap”),myOptions);
//为标记详细信息弹出窗口创建新信息窗口
infowindow=new google.maps.infowindow();
//装载标记
loadMarkers();
}
/**
*通过服务器的ajax请求加载标记
*/
函数loadMarkers(){
//加载标记jSon数据
$.getJSON(标记文件、函数(数据){
//循环所有标记
$.each(data.markers,function(i,item){
//将标记添加到地图
装载标记(项目);
});
});
}
/**
*加载要映射的标记
*/
函数加载标记(markerData)
{
//约会
var mDate=新日期(markerData['created']*1000);
//创建新的标记位置
var mylatng=new google.maps.LatLng(markerData['lat'],markerData['long']);
//创建新标记
var marker=new google.maps.marker({
id:markerData['id'],
地图:地图,
标题:markerData['creator']+'-'+markerData['name'],
位置:myLatlng
});
//将标记添加到稍后用于获取内容和其他标记信息的列表中
markerList[marker.id]=标记器;
var contentString=''+
''+
''+
“'.markerData['name'..””+
''+
“Uluru,也称为艾尔斯岩,是一个大型的”+
“南部的砂岩岩层”+
“澳大利亚中部的北领地。它位于335公里(208英里)处”+
“最近的大城镇艾丽斯·斯普林斯西南部;450 ;公里”+
"(280)英里(约160英里)的公路,卡塔特朱塔和乌鲁鲁是两个主要城市"+
“乌卢鲁-卡塔朱塔国家公园的特征。乌卢鲁是”+
“对Pitjantjatjara和Yankunytjatjara来说是神圣的”+
“该地区的土著居民。这里有许多泉水和水坑,”+
“岩洞和古画。乌鲁鲁被列为世界”+
“遗产地。”+
“归属:乌卢鲁,”+
(上次访问日期为2009年6月22日)。'+
''+
'';
var infowindow=new google.maps.infowindow({
内容:contentString
});
//单击标记时添加事件侦听器
//目前,标记数据包含一个dataurl字段,这当然可以通过不同的方式完成
google.maps.event.addListener(标记'click',函数(){
//单击时显示标记
信息窗口。打开(地图、标记);
map.setZoom(6);
map.setCenter(marker.getPosition());
});
//关闭标记窗口以重置地图位置时添加事件
google.maps.event.addListener(信息窗口,'closeclick',函数(){
});
//将标记添加到列表中
var listItem=$(“”);
$(“”)。attr('href','#')。单击(函数(){
showMarker(marker.id);
返回false;
}).text(markerData['name'])。附录(listItem);
$(“#myMapList”).prepend(列表项);
}
/**
*显示标记信息窗口
*/
函数showMarker(markerId){
//从标记列表中获取标记信息
var marker=markerList[markerId];
//检查是否找到标记
如果(标记){
//从服务器获取标记详细信息
$.get(dataRoot+'data/'+'markernew'+'.html',函数(data){
//显示标记窗口
infowindow.setContent(数据);
map.setZoom(6);
信息窗口。打开(地图、标记);
});
}否则{
警报('未找到错误标记:'+markerId);
}
}
/**
*将新标记添加到列表中
*/
函数newMarker(){
//获取新的城市名称
var markerAddress=$('#newMarker').val();
如果(markerAddress==“”){
$('#newMarker').addClass('error');
$('newMarker').attr('placeholder','missing location');
返回false;
}
//创建用于动态地图查找的新地理编码器
var geocoder=new google.maps.geocoder();
geocoder.geocode({'address':