从JSON构建的对象数组未显示在我的Google地图上 [英] Object array built from JSON not showing up on my Google map

查看:41
本文介绍了从JSON构建的对象数组未显示在我的Google地图上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数据从MySQL提取到网页中,而困在while循环中却看不到.

对于背景,我正在从数据库中提取数据,然后尝试将其放入看起来像这样的对象中:

  var SawtoothPassTrailhead = {名称:"Sawtooth Pass Trailhead",经度:36.453165,长:-118.596751,类型:背包",//标题然后链接seekAdventure:[],博客:[矿山国王环路–红杉国家公园(45英里环路)-背包客评论","https://backpackers-review.com/trip-reports/sequoia-mineral-king/"],youtTube:[]}; 

从数据库调用返回的用于测试的JSON数据如下所示:

  [{"TrailHeadID":"1","TrailHeadName":"Tanner Trail-Grand Canyon","TrailHeadLat":"36.03260","TrailHeadLong":-111.85250","GuideTitle":穿越大峡谷的1周","GuideLink":"https:\/\/www.seekadventure.net \/d \/94-1周穿越大峡谷","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"2","TrailHeadName":"Badger Pass-优胜美地","TrailHeadLat":"37.66480","TrailHeadLong":-119.66340",指南标题":优胜美地国家公园22小时驾车,1.5天的雪鞋行走","GuideLink":"https:\/\/www.seekadventure.net \/d \/79-22-hours-of-driving-1-5-days-snowshoeing-yosemite-nationa","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"2","TrailHeadName":"Badger Pass-优胜美地","TrailHeadLat":"37.66480","TrailHeadLong":-119.66340","GuideTitle":在优胜美地(Socal Hike)r中的雪鞋到杜威点","GuideLink":"https:\/\/socalhiker.net \/snowshoeing到优胜美地中的杜威点\/","GuideMediaType":博客"},{"TrailHeadID":"3","TrailHeadName":"Descanso Beach-Catalina","TrailHeadLat":"33.35040","TrailHeadLong":-118.32820",指南标题":皮划艇露营卡塔利娜岛","GuideLink":"https:\/\/www.seekadventure.net \/d \/76-kayak-camping-catalina-island","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":-118.32620","GuideTitle":"Mini Trans Catalina Trail","GuideLink":"https:\/\/www.seekadventure.net \/d \/73-mini-trans-catalina-trip","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":-118.32620","GuideTitle":对跨卡塔琳娜小径(熊足理论)进行后装","GuideLink":"https:\/\/bearfoottheory.com \/backpacking-the-trans-catalina-trail \/","GuideMediaType":博客"},{"TrailHeadID":"5","TrailHeadName":高塞拉山脉之路","TrailHeadLat":"36.55470","TrailHeadLong":-118.74890","GuideTitle":"High Sierra Trail完整指南","GuideLink":"https:\/\/www.seekadventure.net \/d \/22-california-high-sierra-trail-to-mt-whitney'","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"5","TrailHeadName":高塞拉山脉之路","TrailHeadLat":"36.55470","TrailHeadLong":-118.74890","GuideTitle":"High Sierra Trail(SoCal Hiker)","GuideLink":"https:\/\/socalhiker.net \/-高塞拉利昂山脉概览\/","GuideMediaType":博客"},{"TrailHeadID":"6","TrailHeadName":鹿泉小径-圣哈辛托","TrailHeadLat":"33.75300","TrailHeadLong":-116.72270","GuideTitle":鹿泉小径","GuideLink":"https:\/\/www.seekadventure.net \/d \/26-california-deer-springs-trail-san-jacinto-mountain","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":反射峡谷","TrailHeadLat":"37.25220","TrailHeadLong":-110.97350","GuideTitle":"Reflection Canyon","GuideLink":"https:\/\/www.seekadventure.net \/d \/24-utah-photographing-reflection-canyon","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":反射峡谷","TrailHeadLat":"37.25220","TrailHeadLong":-110.97350","GuideTitle":"Reflection Canyon Backpacking Guide(Clever Hiker)","GuideLink":"https:\/\/www.cleverhiker.com \/blog \/reflection-canyon-backpacking-guide","GuideMediaType":博客"},{"TrailHeadID":"8","TrailHeadName":大松湖-北叉径","TrailHeadLat":"37.12820","TrailHeadLong":-118.42770","GuideTitle":在暴风雪中北叉到内华达山脉第二湖","GuideLink":"https:\/\/www.seekadventure.net \/d \/18-california-north-fork-to-2nd-lake-sierra-neerra-nevada-in-snow-storm","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"8","TrailHeadName":大松湖-北叉径","TrailHeadLat":"37.12820","TrailHeadLong":-118.42770","GuideTitle":通过北叉小径(到峰顶)远足到大松湖","GuideLink":"https:\/\/trailtopeak.com//2017\/07\/09\/hiking-to-big-pine-lakes-via-the-north-fork-rail-trail\/","GuideMediaType":博客"},{"TrailHeadID":"9","TrailHeadName":"Fish Creek Wash Anza Borrego","TrailHeadLat":"33.03872","TrailHeadLong":-116.09941","GuideTitle":在Fish Creek的吉普车洗洗Anza Borrego","GuideLink":"https:\/\/www.seekadventure.net \/d \/99-jeeping-in-fish-creek-wash-anza-borrego","GuideMediaType":"SeekAdventure"}] 

问题是对象的硬编码数组工作正常,但是当我切换到JSON加载的对象数组时,我只会得到一个空白映射.这是我的代码,我可以指出我的故障排除:

  var gmarkers1 = [];var markers1 = [];var markerCluster;var infowindow;var lastmarker = null;var xmlhttp = new XMLHttpRequest();var url ="getMyJSON.php";var SawtoothPassTrailhead = {名称:"Sawtooth Pass Trailhead",经度:36.453165,长:-118.596751,类型:背包",//标题然后链接seekAdventure:[],博客:[矿山国王环路–红杉国家公园(45英里环路)-背包客评论","https://backpackers-review.com/trip-reports/sequoia-mineral-king/"],youtTube:[]};//调用PHP文件并获取JSONxmlhttp.onreadystatechange = function(){如果(this.readyState == 4&& this.status == 200){myFunction(this.responseText);}}xmlhttp.open("GET",url,true);xmlhttp.send();var markers2 = new Array();函数myFunction(response){var arr = JSON.parse(response);var i;var localTrailHeadID;var TrailHeadCounter = 0;var TrailHeadObject;var lastTrailHeadID = 0;//将所有数组都设置为零var seekAdventureCount;var blogsCount;var youtubeCount;var j = 0;//对于mySQL返回的每一行for(i = 0; i< arr.length; i ++){localTrailHeadID = arr [i] .TrailHeadID;//如果上一个Trailhead与当前Trail Head相同,则获取信息并添加到正确的数组中如果(localTrailHeadID == lastTrailHeadID){if(arr [i] .GuideMediaType =="SeekAdventure"){TrailHeadObject.seekAdventureGuideList [seekAdventureCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);seekAdventureCount = seekAdventureCount + 1;TrailHeadObject.seekAdventureGuideList [seekAdventureCount] = arr [i] .GuideLink;seekAdventureCount = seekAdventureCount + 1;}if(arr [i] .GuideMediaType =="blog"){TrailHeadObject.blogGuideList [blogsCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);blogsCount = blogsCount +1;TrailHeadObject.blogGuideList [blogsCount] = arr [i] .GuideLink;blogsCount = blogsCount +1;}if(arr [i] .GuideMediaType =="YouTube"){TrailHeadObject.youTubegGuideList [youtubeCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);youtubeCount = youtubeCount + 1;TrailHeadObject.youTubegGuideList [youtubeCount] = arr [i] .GuideLink;youtubeCount = youtubeCount + 1;}}//创建新对象,然后添加指南以更正数组别的{//将对象添加到标记数组中,但第一轮除外if(j == 0){j = j + 1;}别的{markers1 [trailHeadCounter] = TrailHeadObject;console.log(trailHeadCounter);TrailHeadCounter = TrailHeadCounter + 1;}//创建新的Trailhead对象TrailHeadObject =新的Object();//将数组计数器设置为零var seekAdventureCount = 0;var blogsCount = 0;var youtubeCount = 0;//设置名称lat和longTrailHeadObject.name = arr [i] .TrailHeadName;console.log(arr [i] .TrailHeadName);TrailHeadObject.lat = arr [i] .TrailHeadLat;TrailHeadObject.long = arr [i] .TrailHeadLong;//将TrailHeadObject Guide数组设置为空TrailHeadObject.seekAdventureGuideList = [];TrailHeadObject.blogGuideList = [];TrailHeadObject.youTubegGuideList = [];//添加追踪指南//检查第一个指南媒体类型并添加到正确的数组if(arr [i] .GuideMediaType =="SeekAdventure"){TrailHeadObject.seekAdventureGuideList [seekAdventureCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);seekAdventureCount = seekAdventureCount + 1;TrailHeadObject.seekAdventureGuideList [seekAdventureCount] = arr [i] .GuideLink;seekAdventureCount = seekAdventureCount + 1;}if(arr [i] .GuideMediaType =="blog"){TrailHeadObject.blogGuideList [blogsCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);blogsCount = blogsCount +1;TrailHeadObject.blogGuideList [blogsCount] = arr [i] .GuideLink;blogsCount = blogsCount +1;}if(arr [i] .GuideMediaType =="YouTube"){TrailHeadObject.youTubegGuideList [youtubeCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);youtubeCount = youtubeCount + 1;TrailHeadObject.youTubegGuideList [youtubeCount] = arr [i] .GuideLink;youtubeCount = youtubeCount + 1;}}//结尾else语句//设置最后一个Trailhead IDlastTrailHeadID = localTrailHeadID;}//结束循环}//结束我的功能//markers1 [trailHeadCounter + 1] = TrailHeadObject;//console.log(markers1[trailHeadCounter+1].name);//测试//console.log(markers1[0].name);//console.log(markers1[0].long);//console.log(markers1[0].lat);//处理JSON信息并构建对象并放入markers1 arrray/////////////////////////////////将远足对象添加到数组//////////////////////////////////////markers1 = [//SawtoothPassTrailhead//];/***初始化映射功能*///在查找传递的参数之前,请设置一些默认值//如果没有参数var id;var index = -1;//设置初始地图值var lat = 40.534900;var lng = -101.343789;var zoom = 4;//如果网址eh末尾有任何参数,它们将位于location.search中//看起来像?marker = 3"//跳过第一个字符,我们对?"不感兴趣var query = location.search.substring(1);//将其余部分拆分为每个&"给出"argname = value"对列表的字符var pair = query.split(&");for(var i = 0; i< pairs.length; i ++){//在第一个"="处将每对分开,以获取argname和值var pos = pair [i] .indexOf("=");var argname = pair [i] .substring(0,pos).toLowerCase();var value = pair [i] .substring(pos + 1).toLowerCase();//处理每个可能的argname-如果有空格的可能性,请使用unescape()如果(argname =="id"){id = unescape(value);}如果(argname =="marker"){索引= parseFloat(值);}如果(argname =="lat"){lat = parseFloat(value);}如果(argname =="lng"){lng = parseFloat(value);}如果(argname =="zoom"){zoom = parseInt(value);}如果(argname =="type"){//来自v3文档8/24/2010//混合此地图类型在卫星图像上显示主要街道的透明层.//ROADMAP此地图类型显示普通的街道地图.//卫星此地图类型显示卫星图像.//地形此地图类型显示具有地形和植被等物理特征的地图.如果(值=="m"){maptype = google.maps.MapTypeId.ROADMAP;}if(value =="k"){maptype = google.maps.MapTypeId.SATELLITE;}if(value =="h"){maptype = google.maps.MapTypeId.HYBRID;}if(value =="t"){maptype = google.maps.MapTypeId.TERRAIN;}}}函数makeLink(){var mapinfo ="lat =" + map.getCenter().lat().toFixed(6)+& lng =" + map.getCenter().lng().toFixed(6)+& zoom =" + map.getZoom()+& type =" + MapTypeId2UrlValue(map.getMapTypeId());如果(lastmarker){var a ="https://www.seekadventure.net/adventureMap.html?id=" + lastmarker.id +&"+ mapinfo;var b ="https://www.seekadventure.net/adventureMap.html?marker=" + lastmarker.index +&"+ mapinfo;} 别的 {var a ="https://www.seekadventure.net/adventureMap.html?"+ mapinfo;var b = a;}document.getElementById("idlink").innerHTML ='< a href ='+ a +'" id = url target = _new>共享当前地图视图</a>';}函数MapTypeId2UrlValue(maptype){var urlValue ='m';开关(地图类型){情况google.maps.MapTypeId.HYBRID:urlValue ='h';休息;情况google.maps.MapTypeId.SATELLITE:urlValue ='k';休息;情况google.maps.MapTypeId.TERRAIN:urlValue ='t';休息;默认:情况google.maps.MapTypeId.ROADMAP:urlValue ='m';休息;}返回urlValue;}//----------------------------------------------------------//初始化地图函数initialize(){var center = new google.maps.LatLng(lat,lng);var mapOptions = {缩放:缩放,中心:中心,mapTypeId:google.maps.MapTypeId.TERRAIN};map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);对于(i = 0; i< markers1.length; i ++){console.log(在新的Google地图内部");console.log(markers1 [i] .name);addMarker(markers1 [i]);}infowindow =新的google.maps.InfoWindow({内容: ''});markerCluster = new MarkerClusterer(map,gmarkers1,{imagePath:"https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m"});//首次打开页面时建立链接lastmarker = null;makeLink();//每当地图更改时再次建立链接google.maps.event.addListener(map,'maptypeid_changed',makeLink);google.maps.event.addListener(map,'center_changed',makeLink);google.maps.event.addListener(map,'bounds_changed',makeLink);google.maps.event.addListener(map,'zoom_changed',makeLink);google.maps.event.addListener(map,'click',function(){lastmarker = null;makeLink();infowindow.close();});}/***添加标记到地图的功能*/函数addMarker(marker){var category = marker.type;var title = marker.name;var pos = new google.maps.LatLng(marker.lat,marker.long);var content = BuildBubbleHTML(marker);marker1 =新的google.maps.Marker({标题:标题,位置:pos,类别:类别,地图:地图});gmarkers1.push(marker1);//标记点击监听器google.maps.event.addListener(marker1,'click',(function(marker1,content){return function(){infowindow.setContent(content);infowindow.open(map,marker1);map.panTo(this.getPosition());//map.setZoom(15);}})(marker1,content));}/***用于按类别过滤标记的功能*/filterMarkers =函数(类别){var newmarkers = [];对于(i = 0; i< markers1.length; i ++){标记= gmarkers1 [i];//如果是同一类别或未选择的类别如果(marker.category ==类别|| category.length === 0){marker.setVisible(true);newmarkers.push(marker);}//类别不符别的 {marker.setVisible(false);}}markerCluster.clearMarkers();markerCluster.addMarkers(newmarkers);}//google.maps.event.addDomListener(窗口,加载",初始化);////////////////////////////链接功能//////////////////////////////放在一起弹出气泡html函数BuildBubbleHTML(hike){html =";html = html +'< h6>'+远足名+'</h6>';//如果存在寻求冒险链接if(hike.seekAdventure.length> 0){seekAdventureHTML ='< p>寻找冒险链接</p>';;seekAdventureHTML = seekAdventureHTML +'< ul>'var i;对于(i = 0; i< hierach.seekAdventure.length; i + = 2){seekAdventureHTML = seekAdventureHTML +'< li>';seekAdventureHTML = seekAdventureHTML +'< a href ='+远足.seekAdventure [i + 1] +'" target ="_ blank">';;seekAdventureHTML = seekAdventureHTML + hip.seekAdventure [i] +'</a></li>';;}seekAdventureHTML = seekAdventureHTML +'</ul>';html = html + seekAdventureHTML;}//如果博客链接存在if(hike.blogs.length> 0){blogHTML ='< p>博客链接</p>';blogHTML = blogHTML +'< ul>'var i;对于(i = 0; i< hierblogs.length; i + = 2){blogHTML = blogHTML +'< li>';blogHTML = blogHTML +'< a href ='+远足.blogs [i + 1] +'""target =" _ blank>';;blogHTML = blogHTML + him.blogs [i] +'</a></li>';;}blogHTML = blogHTML +'</ul>';html = html + blogHTML;}返回html;}; 

对我来说,真正奇怪的部分是我在标记功能被调用之前将此日志放进去:

  console.log(在新的Google地图内部");console.log(markers1 [i] .name); 

而且我在控制台中看不到该输出...但是如果我取消注释此行:

 //markers1 = [//SawtoothPassTrailhead//]; 

然后,我已硬编码的一个标记将加载到我的Google地图上.我目前没有看到任何错误,所以我有点卡住了.

解决方案

针对您的JSON响应运行发布的代码时,我收到了JavaScript错误:

  1. 发布的JSON字符串中有多余的'
  2. 从动态响应创建的数据与硬编码对象不匹配.

硬编码对象:

  {//...seekAdventure:[],博客:[]} 

JSON响应会创建以下内容:

  {//...seekAdventureGuideList:[],blogGuideList:[]} 

代码段:

  var gmarkers1 = [];var markers1 = [];var infowindow;var lastmarker = null;var xmlhttp = new XMLHttpRequest();var url ="getMyJSON.php";var SawtoothPassTrailhead = {名称:"Sawtooth Pass Trailhead",经度:36.453165,长:-118.596751,类型:背包",//标题然后链接seekAdventure:[],博客:[矿产国王圈–红杉国家公园(45英里圈)-背包客评论","https://backpackers-review.com/trip-reports/sequoia-mineral-king/"],youtTube:[]};var response ='[{"TrailHeadID":"1","TrailHeadName":"Tanner Trail-Grand Canyon","TrailHeadLat":"36.03260","TrailHeadLong":-111.85250","GuideTitle":"1周穿越大峡谷," GuideLink:" https:\/\/www.seekadventure.net \/d \/94-1-week-traversing-the-grand-canyon," GuideMediaType:" SeekAdventure},{"TrailHeadID":"2","TrailHeadName":"Badger Pass-Yosemite","TrailHeadLat":"37.66480","TrailHeadLong":-119.66340","GuideTitle":"22小时的驾驶,1.5天优胜美地国家公园雪鞋博物馆","GuideLink":"https:\/\/www.seekadventure.net \/d \/79-22-hours-of-driving-1-5 days-of-snowshoeing-yosemite-nationa," GuideMediaType:" SeekAdventure},{" TrailHeadID:" 2," TrailHeadName:" Badger Pass-Yosemite," TrailHeadLat:" 37.66480," TrailHeadLong:"-119.66340,"GuideTitle":在优胜美地(Socal Hike)r中的雪鞋到杜威点","GuideLink":"https:\/\/socalhiker.net \/在优胜美地中的雪鞋到杜威点\/","GuideMediaType:"博客},{" TrailHeadID:" 3," TrailHeadName:" Descanso Beach-Catalina","TrailHeadLat":"33.35040","TrailHeadLong":-118.32820","GuideTitle":"Kayak Camping Catalina Island","GuideLink":"https:\/\/www.seekadventure.net \/d\/76-kayak-camping-catalina-island," GuideMediaType:" SeekAdventure},{" TrailHeadID:" 4," TrailHeadName:" Trans Catalina Trail," TrailHeadLat:" 33.34030,"TrailHeadLong:"-118.32620," GuideTitle:" Mini Trans Catalina Trail," GuideLink:" https:\/\/www.seekadventure.net \/d \/73-mini-trans-catalina-trip","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":-118.32620","GuideTitle":对跨卡塔琳娜小径(熊足理论)进行背包装箱","GuideLink":"https:\/\/bearfoottheory.com \/backpacking-the-trans-catalina-trail \/","GuideMediaType":博客"},{"TrailHeadID":"5","TrailHeadName":"High Sierra Trail","TrailHeadLat":" 36.55470," TrailHeadLong:"-118.74890," GuideTitle:" High Sierra Trail完整指南,"GuideLink:" https:\/\/www.seekadventure.net \/d \/22-california-high-sierra-rail-to-mt-whitney," GuideMediaType:" SeekAdventure},{" TrailHeadID:" 5," TrailHeadName:" High Sierra Trail," TrailHeadLat:" 36.55470","TrailHeadLong":-118.74890","GuideTitle":塞拉利昂之路(SoCal Hiker)","GuideLink":"https:\/\/socalhiker.net \/-high-sierra-Trail \/," GuideMediaType:" blog},{" TrailHeadID:" 6," TrailHeadName:" Deer Springs Trail-San Jacinto," TrailHeadLat:" 33.75300," TrailHeadLong:"-116.72270," GuideTitle:" Deer Springs Trail," GuideLink:" https:\/\/www.seekadventure.net \/d \/26-california-deer-springs-trail-san-jacinto-mountain","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":"Reflection Canyon","TrailHeadLat":"37.25220","TrailHeadLong":-110.97350","GuideTitle":反射峡谷","GuideLink":"https:\/\/www.seekadventure.net \/d \/24-utah-photographing-reflection-canyon","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":反射峡谷","TrailHeadLat":"37.25220","TrailHeadLong":-110.97350," GuideTitle:" Reflection Canyon背包指南(聪明的徒步旅行者)," GuideLink:" https:\/\/www.cleverhiker.com \/blog \/reflection-canyon-backpacking-guide," GuideMediaType":博客"},{"TrailHeadID":"8","TrailHeadName":大松湖-北叉径","TrailHeadLat":"37.12820","TrailHeadLong":-118.42770","GuideTitle":北叉到第二场内华达山脉内的暴风雪中","GuideLink":"https:\/\/www.seekadventure.net \/d \/18-california-north-fork-to-2nd-lake-sierra-nevada-in-snow-storm," GuideMediaType:" SeekAdventure},{" TrailHeadID:" 8," TrailHeadName:" Big Pine Lakes-North Fork Trail," TrailHeadLat:" 37.12820," TrailHeadLong:"-118.42770," GuideTitle:"通过北叉小径远足(前往峰顶)到大松湖," GuideLink:" https:\/\/trailtopeak.com \/2017\/07 \/09 \/通过北叉拖车远足到大松树湖"/","GuideMediaType":"blog"},{"TrailHeadID":"9","TrailHeadName:" Fish Creek Wash Anza Borrego," TrailHeadLat:" 33.03872," TrailHeadLong:"-116.09941," GuideTitle:" J潜入Fish Creek Wash Anza Borrego中","GuideLink":"https:\/\/www.seekadventure.net \/d \/99-jeeping-in-fish-creek-wash-anza-borrego","GuideMediaType":" SeekAdventure}]';;myFunction(response);var markers2 = new Array();函数myFunction(response){var arr = JSON.parse(response);var i;var localTrailHeadID;var TrailHeadCounter = 0;var TrailHeadObject;var lastTrailHeadID = 0;//将所有数组都设置为零var seekAdventureCount;var blogsCount;var youtubeCount;var j = 0;//对于mySQL返回的每一行for(i = 0; i< arr.length; i ++){localTrailHeadID = arr [i] .TrailHeadID;//如果上一个Trailhead与当前Trail Head相同,则获取信息并添加到正确的数组中如果(localTrailHeadID == lastTrailHeadID){如果(arr [i] .GuideMediaType =="SeekAdventure"){TrailHeadObject.seekAdventureGuideList [seekAdventureCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);seekAdventureCount = seekAdventureCount + 1;TrailHeadObject.seekAdventureGuideList [seekAdventureCount] = arr [i] .GuideLink;seekAdventureCount = seekAdventureCount + 1;}如果(arr [i] .GuideMediaType =="blog"){TrailHeadObject.blogGuideList [blogsCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);blogsCount = blogsCount +1;TrailHeadObject.blogGuideList [blogsCount] = arr [i] .GuideLink;blogsCount = blogsCount +1;}如果(arr [i] .GuideMediaType =="YouTube"){TrailHeadObject.youTubegGuideList [youtubeCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);youtubeCount = youtubeCount + 1;TrailHeadObject.youTubegGuideList [youtubeCount] = arr [i] .GuideLink;youtubeCount = youtubeCount + 1;}}//创建新对象,然后添加指南以更正数组别的 {//将对象添加到标记数组中,但第一轮除外如果(j == 0){j = j + 1;} 别的 {markers1 [trailHeadCounter] = TrailHeadObject;console.log(trailHeadCounter);TrailHeadCounter = TrailHeadCounter + 1;}//创建新的Trailhead对象TrailHeadObject =新的Object();//将数组计数器设置为零var seekAdventureCount = 0;var blogsCount = 0;var youtubeCount = 0;//设置名称lat和longTrailHeadObject.name = arr [i] .TrailHeadName;console.log(arr [i] .TrailHeadName);TrailHeadObject.lat = arr [i] .TrailHeadLat;TrailHeadObject.long = arr [i] .TrailHeadLong;//将TrailHeadObject Guide数组设置为空TrailHeadObject.seekAdventureGuideList = [];TrailHeadObject.blogGuideList = [];TrailHeadObject.youTubegGuideList = [];//添加追踪指南//检查第一个指南媒体类型并添加到正确的数组如果(arr [i] .GuideMediaType =="SeekAdventure"){TrailHeadObject.seekAdventureGuideList [seekAdventureCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);seekAdventureCount = seekAdventureCount + 1;TrailHeadObject.seekAdventureGuideList [seekAdventureCount] = arr [i] .GuideLink;seekAdventureCount = seekAdventureCount + 1;}如果(arr [i] .GuideMediaType =="blog"){TrailHeadObject.blogGuideList [blogsCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);blogsCount = blogsCount +1;TrailHeadObject.blogGuideList [blogsCount] = arr [i] .GuideLink;blogsCount = blogsCount +1;}如果(arr [i] .GuideMediaType =="YouTube"){TrailHeadObject.youTubegGuideList [youtubeCount] = arr [i] .GuideTitle;console.log(arr [i] .GuideTitle);youtubeCount = youtubeCount + 1;TrailHeadObject.youTubegGuideList [youtubeCount] = arr [i] .GuideLink;youtubeCount = youtubeCount + 1;}}//结尾else语句//设置最后一个Trailhead IDlastTrailHeadID = localTrailHeadID;}//结束循环}//结束我的功能//处理JSON信息并构建对象并放入markers1 arrray/////////////////////////////////将远足对象添加到数组/////////////////////////////////////***初始化映射功能*///在查找传递的参数之前,请设置一些默认值//如果没有参数var id;var index = -1;//设置初始地图值var lat = 40.534900;var lng = -101.343789;var zoom = 4;//如果网址eh末尾有任何参数,它们将位于location.search中//看起来像?marker = 3"//跳过第一个字符,我们对?"不感兴趣var query = location.search.substring(1);//将其余部分拆分为每个&"给出"argname = value"对列表的字符var pair = query.split(&");for(var i = 0; i< pairs.length; i ++){//在第一个"="处将每对分开,以获取argname和值var pos = pair [i] .indexOf("=");var argname = pair [i] .substring(0,pos).toLowerCase();var value = pair [i] .substring(pos + 1).toLowerCase();//处理每个可能的argname-如果有空格的可能性,请使用unescape()如果(argname =="id"){id = unescape(value);}如果(argname =="marker"){索引= parseFloat(值);}如果(argname =="lat"){lat = parseFloat(value);}如果(argname =="lng"){lng = parseFloat(value);}如果(argname =="zoom"){zoom = parseInt(value);}如果(argname =="type"){//来自v3文档8/24/2010//混合此地图类型在卫星图像上显示主要街道的透明层.//ROADMAP此地图类型显示普通的街道地图.//卫星此地图类型显示卫星图像.//地形此地图类型显示具有地形和植被等物理特征的地图.如果(值=="m"){maptype = google.maps.MapTypeId.ROADMAP;}if(value =="k"){maptype = google.maps.MapTypeId.SATELLITE;}if(value =="h"){maptype = google.maps.MapTypeId.HYBRID;}if(value =="t"){maptype = google.maps.MapTypeId.TERRAIN;}}}函数makeLink(){var mapinfo ="lat =" + map.getCenter().lat().toFixed(6)+& lng =" + map.getCenter().lng().toFixed(6)+& zoom =" + map.getZoom()+& type =" + MapTypeId2UrlValue(map.getMapTypeId());如果(lastmarker){var a ="https://www.seekadventure.net/adventureMap.html?id=" + lastmarker.id +&"+ mapinfo;var b ="https://www.seekadventure.net/adventureMap.html?marker=" + lastmarker.index +&"+ mapinfo;} 别的 {var a ="https://www.seekadventure.net/adventureMap.html?"+ mapinfo;var b = a;}document.getElementById("idlink").innerHTML ='< a href ='+ a +'" id = url target = _new>共享当前地图视图</a>';;}函数MapTypeId2UrlValue(maptype){var urlValue ='m';开关(地图类型){情况google.maps.MapTypeId.HYBRID:urlValue ='h';休息;情况google.maps.MapTypeId.SATELLITE:urlValue ='k';休息;情况google.maps.MapTypeId.TERRAIN:urlValue ='t';休息;默认:情况google.maps.MapTypeId.ROADMAP:urlValue ='m';休息;}返回urlValue;}//----------------------------------------------------------//初始化地图函数initialize(){var center = new google.maps.LatLng(lat,lng);var mapOptions = {缩放:缩放,中心:中心,mapTypeId:google.maps.MapTypeId.TERRAIN};map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);对于(i = 0; i< markers1.length; i ++){console.log(在新的Google地图内部");console.log(markers1 [i] .name);addMarker(markers1 [i]);}infowindow =新的google.maps.InfoWindow({内容: ''});//首次打开页面时建立链接lastmarker = null;makeLink();//每当地图更改时再次建立链接google.maps.event.addListener(map,'maptypeid_changed',makeLink);google.maps.event.addListener(map,'center_changed',makeLink);google.maps.event.addListener(map,'bounds_changed',makeLink);google.maps.event.addListener(map,'zoom_changed',makeLink);google.maps.event.addListener(map,'click',function(){lastmarker = null;makeLink();infowindow.close();});}/***添加标记到地图的功能*/函数addMarker(marker){var category = marker.type;var title = marker.name;var pos = new google.maps.LatLng(marker.lat,marker.long);var content = BuildBubbleHTML(marker);marker1 =新的google.maps.Marker({标题:标题,位置:pos,类别:类别,地图:地图});gmarkers1.push(marker1);//标记点击监听器google.maps.event.addListener(marker1,'click',(function(marker1,content){return function(){infowindow.setContent(content);infowindow.open(map,marker1);map.panTo(this.getPosition());//map.setZoom(15);}})(marker1,content));}////////////////////////////链接功能//////////////////////////////放在一起弹出气泡html函数BuildBubbleHTML(hike){html =";html = html +'< h6>'+远足名+'</h6>';console.log(hike);//如果存在寻求冒险链接如果(hike.seekAdventureGuideList.length> 0){seekAdventureHTML ='< p>寻找冒险链接</p>';;seekAdventureHTML = seekAdventureHTML +'< ul>'var i;对于(i = 0; i< hierach.seekAdventureGuideList.length; i + = 2){seekAdventureHTML = seekAdventureHTML +'< li>';seekAdventureHTML = seekAdventureHTML +'< a href ='+远足.seekAdventureGuideList [i + 1] +'" target ="_ blank">';;seekAdventureHTML = seekAdventureHTML + hip.seekAdventureGuideList [i] +'</a></li>';;}seekAdventureHTML = seekAdventureHTML +'</ul>';html = html + seekAdventureHTML;}//如果博客链接存在如果(hike.blogGuideList.length> 0){blogHTML ='< p>博客链接</p>';blogHTML = blogHTML +'< ul>'var i;对于(i = 0; i< hierach.blogGuideList.length; i + = 2){blogHTML = blogHTML +'< li>';blogHTML = blogHTML +'< a href ='+远足.blogGuideList [i + 1] +'""target =" _ blank>';;blogHTML = blogHTML + him.blogGuideList [i] +'</a></li>';;}blogHTML = blogHTML +'</ul>';html = html + blogHTML;}返回html;};  

  html,身体,#map-canvas {高度:100%;边距:0;填充:0;}  

 < div id ="map-canvas"></div><!-用您自己的API密钥替换key参数的值.->< script src ="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=初始化异步延迟"</script>< div id ="idlink" style ="display:none"></div>  

I am pulling data from MySQL into a web page and I can not see while I am stuck in my while loop.

For background I am pulling data from my database and trying to put it into objects that look something like this:

var SawtoothPassTrailhead = {
  name: "Sawtooth Pass Trailhead",
  lat:  36.453165,
  long:  -118.596751,
  type: "backpacking", 

  //Title then link
  seekAdventure: [],
  blogs: ['Mineral King Loop â€" Sequoia National Park (45 Mile Loop) - Backpackers Review' , 'https://backpackers-review.com/trip-reports/sequoia-mineral-king/'],
  youtTube: []
};

The JSON data that is coming back from my DB call for my test looks like this:

[
{"TrailHeadID":"1",
 "TrailHeadName":"Tanner Trail - Grand Canyon",
 "TrailHeadLat":"36.03260",
 "TrailHeadLong":"-111.85250",
 "GuideTitle":"1 Week Traversing the Grand Canyon",
 "GuideLink":"https:\/\/www.seekadventure.net\/d\/94-1-week-traversing-the-grand-canyon",
 "GuideMediaType":"SeekAdventure"
},{
 "TrailHeadID":"2",
 "TrailHeadName":"Badger Pass - Yosemite",
 "TrailHeadLat":"37.66480",
 "TrailHeadLong":"-119.66340",
 "GuideTitle":"22 Hours of Driving, 1.5 Days of Snowshoeing, Yosemite National Park",
 "GuideLink":"https:\/\/www.seekadventure.net\/d\/79-22-hours-of-driving-1-5-days-of-snowshoeing-yosemite-nationa",
 "GuideMediaType":"SeekAdventure"
},{
 "TrailHeadID":"2",
 "TrailHeadName":"Badger Pass - Yosemite",
 "TrailHeadLat":"37.66480",
 "TrailHeadLong":"-119.66340",
 "GuideTitle":"Snowshoeing to Dewey Point in Yosemite (Socal Hike)r",
 "GuideLink":"https:\/\/socalhiker.net\/snowshoeing-to-dewey-point-in-yosemite\/",
 "GuideMediaType":"blog"
},{
 "TrailHeadID":"3",
 "TrailHeadName":"Descanso Beach - Catalina",
 "TrailHeadLat":"33.35040",
 "TrailHeadLong":"-118.32820",
 "GuideTitle":"Kayak Camping Catalina Island",
 "GuideLink":"https:\/\/www.seekadventure.net\/d\/76-kayak-camping-catalina-island",
 "GuideMediaType":"SeekAdventure"
},{
 "TrailHeadID":"4",
 "TrailHeadName":"Trans Catalina Trail",
 "TrailHeadLat":"33.34030",
 "TrailHeadLong":"-118.32620",
 "GuideTitle":"Mini Trans Catalina Trail",
 "GuideLink":"https:\/\/www.seekadventure.net\/d\/73-mini-trans-catalina-trip",
 "GuideMediaType":"SeekAdventure"
},{
 "TrailHeadID":"4",
 "TrailHeadName":"Trans Catalina Trail",
 "TrailHeadLat":"33.34030",
 "TrailHeadLong":"-118.32620",
 "GuideTitle":"Backpacking the Trans-Catalina Trail (Bearfoot Theory)",
 "GuideLink":"https:\/\/bearfoottheory.com\/backpacking-the-trans-catalina-trail\/",
 "GuideMediaType":"blog"
},{
 "TrailHeadID":"5",
 "TrailHeadName":"High Sierra Trail",
 "TrailHeadLat":"36.55470",
 "TrailHeadLong":"-118.74890",
 "GuideTitle":"High Sierra Trail Complete Guide",
 "GuideLink":"https:\/\/www.seekadventure.net\/d\/22-california-high-sierra-trail-to-mt-whitney'",
 "GuideMediaType":"SeekAdventure"
},{
 "TrailHeadID":"5",
 "TrailHeadName":"High Sierra Trail",
 "TrailHeadLat":"36.55470",
 "TrailHeadLong":"-118.74890",
 "GuideTitle":"High Sierra Trail (SoCal Hiker)",
 "GuideLink":"https:\/\/socalhiker.net\/overview-of-the-high-sierra-trail\/",
 "GuideMediaType":"blog"
},{
 "TrailHeadID":"6",
 "TrailHeadName":"Deer Springs Trail - San Jacinto",
 "TrailHeadLat":"33.75300",
 "TrailHeadLong":"-116.72270",
 "GuideTitle":"Deer Springs Trail",
 "GuideLink":"https:\/\/www.seekadventure.net\/d\/26-california-deer-springs-trail-san-jacinto-mountain",
 "GuideMediaType":"SeekAdventure"
},{
 "TrailHeadID":"7",
 "TrailHeadName":"Reflection Canyon",
 "TrailHeadLat":"37.25220",
 "TrailHeadLong":"-110.97350",
 "GuideTitle":"Reflection Canyon",
 "GuideLink":"https:\/\/www.seekadventure.net\/d\/24-utah-photographing-reflection-canyon",
 "GuideMediaType":"SeekAdventure"
},{
 "TrailHeadID":"7",
 "TrailHeadName":"Reflection Canyon",
 "TrailHeadLat":"37.25220",
 "TrailHeadLong":"-110.97350",
 "GuideTitle":"Reflection Canyon Backpacking Guide (Clever Hiker)",
 "GuideLink":"https:\/\/www.cleverhiker.com\/blog\/reflection-canyon-backpacking-guide",
 "GuideMediaType":"blog"
},{
 "TrailHeadID":"8",
 "TrailHeadName":"Big Pine Lakes - North Fork Trail",
 "TrailHeadLat":"37.12820",
 "TrailHeadLong":"-118.42770",
 "GuideTitle":"North Fork to 2nd Lake Sierra Nevada in a Snow Storm",
 "GuideLink":"https:\/\/www.seekadventure.net\/d\/18-california-north-fork-to-2nd-lake-sierra-nevada-in-a-snow-storm",
 "GuideMediaType":"SeekAdventure"
},{
 "TrailHeadID":"8",
 "TrailHeadName":"Big Pine Lakes - North Fork Trail",
 "TrailHeadLat":"37.12820",
 "TrailHeadLong":"-118.42770",
 "GuideTitle":"Hiking To Big Pine Lakes via The North Fork Trail (Trail to Peak)",
 "GuideLink":"https:\/\/trailtopeak.com\/2017\/07\/09\/hiking-to-big-pine-lakes-via-the-north-fork-trail\/",
 "GuideMediaType":"blog"
},{
 "TrailHeadID":"9",
 "TrailHeadName":"Fish Creek Wash Anza Borrego",
 "TrailHeadLat":"33.03872",
 "TrailHeadLong":"-116.09941",
 "GuideTitle":"Jeeping in Fish Creek Wash Anza Borrego","GuideLink":"https:\/\/www.seekadventure.net\/d\/99-jeeping-in-fish-creek-wash-anza-borrego",
 "GuideMediaType":"SeekAdventure"
}]

The problem is the hardcoded array of objects works fine but when I switch to my JSON loaded object array I just get a blank map. Here is my code and I can point out my troubleshooting:

var gmarkers1 = [];
var markers1 = [];
var markerCluster;
var infowindow;
var lastmarker = null;
var xmlhttp = new XMLHttpRequest();
var url = "getMyJSON.php";


var SawtoothPassTrailhead = {
  name: "Sawtooth Pass Trailhead",
  lat:  36.453165,
  long:  -118.596751,
  type: "backpacking", 

  //Title then link
  seekAdventure: [],
  blogs: ['Mineral King Loop â€" Sequoia National Park (45 Mile Loop) - Backpackers Review' , 'https://backpackers-review.com/trip-reports/sequoia-mineral-king/'],
  youtTube: []
};

//Call PHP file and get JSON

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

var markers2 = new Array();


function myFunction(response) {
    var arr = JSON.parse(response);
    var i;
    var localTrailHeadID;
    var trailHeadCounter = 0;
    var TrailHeadObject;
    var lastTrailHeadID = 0;

    //set array conts all to zero
    var seekAdventureCount;
    var blogsCount;
    var youtubeCount;

    var j = 0;


    //for each row returned by mySQL
    for(i = 0; i < arr.length; i++){
      localTrailHeadID = arr[i].TrailHeadID;

      //if previuse trailhead is the same as the current trail head get info and add to correct array
      if (localTrailHeadID == lastTrailHeadID){
        if(arr[i].GuideMediaType == "SeekAdventure"){
          TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideTitle;
          console.log(arr[i].GuideTitle);
          seekAdventureCount = seekAdventureCount + 1;
          TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideLink;
          seekAdventureCount = seekAdventureCount + 1;
        }
        if(arr[i].GuideMediaType == "blog"){
          TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideTitle;
          console.log(arr[i].GuideTitle);
          blogsCount = blogsCount + 1;
          TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideLink;
          blogsCount = blogsCount + 1;
        }
        if(arr[i].GuideMediaType == "YouTube"){
          TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideTitle;
          console.log(arr[i].GuideTitle);
          youtubeCount = youtubeCount + 1;
          TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideLink;
          youtubeCount = youtubeCount + 1;
        }

      }

      //create new object and then add guide to correct array
      else{

        //add object to array of markers except on first round
        if(j == 0){
          j = j + 1;
        }
        else{
          markers1[trailHeadCounter] = TrailHeadObject;
          console.log(trailHeadCounter);

          trailHeadCounter = trailHeadCounter + 1;
        }

        //create new trailhead object
        TrailHeadObject = new Object();

        //set array counters to zero
        var seekAdventureCount =0;
        var blogsCount = 0;
        var youtubeCount = 0;

        //set name lat and long
        TrailHeadObject.name = arr[i].TrailHeadName;
        console.log(arr[i].TrailHeadName);
        TrailHeadObject.lat = arr[i].TrailHeadLat;
        TrailHeadObject.long = arr[i].TrailHeadLong;

        //set TrailHeadObject Guide arrays to empty
        TrailHeadObject.seekAdventureGuideList = [];
        TrailHeadObject.blogGuideList = [];
        TrailHeadObject.youTubegGuideList = [];

        //Add trail Guide
        //check first guide media type and add to correct Array
        if(arr[i].GuideMediaType == "SeekAdventure"){
          TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideTitle;
          console.log(arr[i].GuideTitle);
          seekAdventureCount = seekAdventureCount + 1;
          TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideLink;
          seekAdventureCount = seekAdventureCount + 1;
        }
        if(arr[i].GuideMediaType == "blog"){
          TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideTitle;
          console.log(arr[i].GuideTitle);
          blogsCount = blogsCount + 1;
          TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideLink;
          blogsCount = blogsCount + 1;
        }
        if(arr[i].GuideMediaType == "YouTube"){
          TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideTitle;
          console.log(arr[i].GuideTitle);
          youtubeCount = youtubeCount + 1;
          TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideLink;
          youtubeCount = youtubeCount + 1;
        }

      } // end else statement


      //set last trailhead ID
      lastTrailHeadID = localTrailHeadID;




    }//end for Loop

} //end my function

//markers1[trailHeadCounter+1] = TrailHeadObject;
//console.log(markers1[trailHeadCounter+1].name);


//testing
//console.log(markers1[0].name);
//console.log(markers1[0].long);
//console.log(markers1[0].lat);




//Proceses JSON Info and build Objects and place into markers1 arrray


///////////////////////////////
//add Hike Objects to Array////
///////////////////////////////

//markers1 = [
  //SawtoothPassTrailhead
//];


/**
 * Function to init map
 */

// Before we go looking for the passed parameters, set some defaults
// in case there are no parameters
var id;
var index = -1;

//set initial map values
var lat = 40.534900;
var lng = -101.343789;
var zoom = 4;

// If there are any parameters at eh end of the URL, they will be in  location.search
// looking something like  "?marker=3"

// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);

// split the rest at each "&" character to give a list of  "argname=value"  pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
  // break each pair at the first "=" to obtain the argname and value
  var pos = pairs[i].indexOf("=");
  var argname = pairs[i].substring(0, pos).toLowerCase();
  var value = pairs[i].substring(pos + 1).toLowerCase();

  // process each possible argname  -  use unescape() if theres any chance of spaces
  if (argname == "id") {
    id = unescape(value);
  }
  if (argname == "marker") {
    index = parseFloat(value);
  }
  if (argname == "lat") {
    lat = parseFloat(value);
  }
  if (argname == "lng") {
    lng = parseFloat(value);
  }
  if (argname == "zoom") {
    zoom = parseInt(value);
  }
  if (argname == "type") {
    // from the v3 documentation 8/24/2010
    // HYBRID This map type displays a transparent layer of major streets on satellite images. 
    // ROADMAP This map type displays a normal street map. 
    // SATELLITE This map type displays satellite images. 
    // TERRAIN This map type displays maps with physical features such as terrain and vegetation. 
    if (value == "m") {
      maptype = google.maps.MapTypeId.ROADMAP;
    }
    if (value == "k") {
      maptype = google.maps.MapTypeId.SATELLITE;
    }
    if (value == "h") {
      maptype = google.maps.MapTypeId.HYBRID;
    }
    if (value == "t") {
      maptype = google.maps.MapTypeId.TERRAIN;
    }
  }
}

function makeLink() {
  var mapinfo = "lat=" + map.getCenter().lat().toFixed(6) +
    "&lng=" + map.getCenter().lng().toFixed(6) +
    "&zoom=" + map.getZoom() +
    "&type=" + MapTypeId2UrlValue(map.getMapTypeId());
  if (lastmarker) {
    var a = "https://www.seekadventure.net/adventureMap.html?id=" + lastmarker.id + "&" + mapinfo;
    var b = "https://www.seekadventure.net/adventureMap.html?marker=" + lastmarker.index + "&" + mapinfo;
  } else {
    var a = "https://www.seekadventure.net/adventureMap.html?" + mapinfo;
    var b = a;
  }

  document.getElementById("idlink").innerHTML = '<a href="' + a + '" id=url target=_new>Share Current Map View</a>';
}

function MapTypeId2UrlValue(maptype) {
  var urlValue = 'm';
  switch (maptype) {
    case google.maps.MapTypeId.HYBRID:
      urlValue = 'h';
      break;
    case google.maps.MapTypeId.SATELLITE:
      urlValue = 'k';
      break;
    case google.maps.MapTypeId.TERRAIN:
      urlValue = 't';
      break;
    default:
    case google.maps.MapTypeId.ROADMAP:
      urlValue = 'm';
      break;
  }
  return urlValue;
}


//----------------------------------------------------------

//initialize map 
function initialize() {
  var center = new google.maps.LatLng(lat, lng);
  var mapOptions = {
    zoom: zoom,
    center: center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  for (i = 0; i < markers1.length; i++) {
    console.log("inside new google map");
    console.log(markers1[i].name);
    addMarker(markers1[i]);
  }

infowindow = new google.maps.InfoWindow({
  content: ''
});

  markerCluster = new MarkerClusterer(map, gmarkers1, {
    imagePath: 'https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m'
  });

// Make the link the first time when the page opens
  lastmarker = null;
  makeLink();

  // Make the link again whenever the map changes
  google.maps.event.addListener(map, 'maptypeid_changed', makeLink);
  google.maps.event.addListener(map, 'center_changed', makeLink);
  google.maps.event.addListener(map, 'bounds_changed', makeLink);
  google.maps.event.addListener(map, 'zoom_changed', makeLink);

  google.maps.event.addListener(map, 'click', function() {
    lastmarker = null;
    makeLink();
    infowindow.close();
  });



}

/**
 * Function to add marker to map
 */

function addMarker(marker) {
  var category = marker.type;
  var title = marker.name;
  var pos = new google.maps.LatLng(marker.lat, marker.long);
  var content = BuildBubbleHTML(marker);

  marker1 = new google.maps.Marker({
    title: title,
    position: pos,
    category: category,
    map: map
  });

  gmarkers1.push(marker1);

  // Marker click listener
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
    return function() {
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
      //map.setZoom(15);
    }
  })(marker1, content));
}

/**
 * Function to filter markers by category
 */

filterMarkers = function(category) {
  var newmarkers = [];
  for (i = 0; i < markers1.length; i++) {
    marker = gmarkers1[i];
    // If is same category or category not picked
    if (marker.category == category || category.length === 0) {
      marker.setVisible(true);
      newmarkers.push(marker);
    }
    // Categories don't match 
    else {
      marker.setVisible(false);
    }
  }
  markerCluster.clearMarkers();
  markerCluster.addMarkers(newmarkers);
}
//google.maps.event.addDomListener(window, "load", initialize);


/////////////////////////
///Functions For Links///
/////////////////////////

//put pop up bubble html together 
function BuildBubbleHTML(hike){
    html = "";
    html = html +'<h6>'  + hike.name + '</h6>';

    //If Seek Adventure Links Exist
    if(hike.seekAdventure.length > 0){
        seekAdventureHTML = '<p>Seek Adventure Links</p>';
        seekAdventureHTML = seekAdventureHTML + '<ul>'
        var i;
        for (i = 0; i < hike.seekAdventure.length; i+=2) { 
            seekAdventureHTML = seekAdventureHTML + '<li>';
            seekAdventureHTML = seekAdventureHTML + '<a href="' + hike.seekAdventure[i+1] + '"target="_blank">';
            seekAdventureHTML = seekAdventureHTML + hike.seekAdventure[i] + '</a></li>';
        } 
        seekAdventureHTML = seekAdventureHTML + '</ul>';
        html = html + seekAdventureHTML;
    }

    //If Blog Links Exist
    if(hike.blogs.length > 0){
        blogHTML = '<p>Blog Links</p>';
        blogHTML = blogHTML + '<ul>'
        var i;
        for (i = 0; i < hike.blogs.length; i+=2) { 
            blogHTML = blogHTML + '<li>';
            blogHTML = blogHTML + '<a href="' + hike.blogs[i+1] + '""target="_blank">';
            blogHTML = blogHTML + hike.blogs[i] + '</a></li>';
        } 
        blogHTML = blogHTML + '</ul>';
        html = html + blogHTML;
    }


    return html;
};

The really odd part to me is I put this log in right before the marker function is called:

console.log("inside new google map");
console.log(markers1[i].name);

And I do not see that output in the console... But if I uncomment out this line:

//markers1 = [
  //SawtoothPassTrailhead
//];

Then the one marker I have hardcoded will load on my Google Map. I am not seeing any errors at this point so I am a little stuck.

解决方案

I get javascript errors when I run the posted code against your JSON response:

  1. there is an extraneous ' in the posted JSON string
  2. The data created from your dynamic response doesn't match the hardcoded object.

hardcoded object:

{
  // ...
  seekAdventure: [],
  blogs: [] 
}

JSON response creates this:

{
  // ...
  seekAdventureGuideList: [],
  blogGuideList: [] 
}

proof of concept fiddle

code snippet:

var gmarkers1 = [];
var markers1 = [];
var infowindow;
var lastmarker = null;
var xmlhttp = new XMLHttpRequest();
var url = "getMyJSON.php";


var SawtoothPassTrailhead = {
  name: "Sawtooth Pass Trailhead",
  lat: 36.453165,
  long: -118.596751,
  type: "backpacking",

  //Title then link
  seekAdventure: [],
  blogs: ['Mineral King Loop â€" Sequoia National Park (45 Mile Loop) - Backpackers Review', 'https://backpackers-review.com/trip-reports/sequoia-mineral-king/'],
  youtTube: []
};

var response = '[{"TrailHeadID":"1","TrailHeadName":"Tanner Trail - Grand Canyon","TrailHeadLat":"36.03260","TrailHeadLong":"-111.85250","GuideTitle":"1 Week Traversing the Grand Canyon","GuideLink":"https:\/\/www.seekadventure.net\/d\/94-1-week-traversing-the-grand-canyon","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"2","TrailHeadName":"Badger Pass - Yosemite","TrailHeadLat":"37.66480","TrailHeadLong":"-119.66340","GuideTitle":"22 Hours of Driving, 1.5 Days of Snowshoeing, Yosemite National Park","GuideLink":"https:\/\/www.seekadventure.net\/d\/79-22-hours-of-driving-1-5-days-of-snowshoeing-yosemite-nationa","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"2","TrailHeadName":"Badger Pass - Yosemite","TrailHeadLat":"37.66480","TrailHeadLong":"-119.66340","GuideTitle":"Snowshoeing to Dewey Point in Yosemite (Socal Hike)r","GuideLink":"https:\/\/socalhiker.net\/snowshoeing-to-dewey-point-in-yosemite\/","GuideMediaType":"blog"},{"TrailHeadID":"3","TrailHeadName":"Descanso Beach - Catalina","TrailHeadLat":"33.35040","TrailHeadLong":"-118.32820","GuideTitle":"Kayak Camping Catalina Island","GuideLink":"https:\/\/www.seekadventure.net\/d\/76-kayak-camping-catalina-island","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":"-118.32620","GuideTitle":"Mini Trans Catalina Trail","GuideLink":"https:\/\/www.seekadventure.net\/d\/73-mini-trans-catalina-trip","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":"-118.32620","GuideTitle":"Backpacking the Trans-Catalina Trail (Bearfoot Theory)","GuideLink":"https:\/\/bearfoottheory.com\/backpacking-the-trans-catalina-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"5","TrailHeadName":"High Sierra Trail","TrailHeadLat":"36.55470","TrailHeadLong":"-118.74890","GuideTitle":"High Sierra Trail Complete Guide","GuideLink":"https:\/\/www.seekadventure.net\/d\/22-california-high-sierra-trail-to-mt-whitney","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"5","TrailHeadName":"High Sierra Trail","TrailHeadLat":"36.55470","TrailHeadLong":"-118.74890","GuideTitle":"High Sierra Trail (SoCal Hiker)","GuideLink":"https:\/\/socalhiker.net\/overview-of-the-high-sierra-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"6","TrailHeadName":"Deer Springs Trail - San Jacinto","TrailHeadLat":"33.75300","TrailHeadLong":"-116.72270","GuideTitle":"Deer Springs Trail","GuideLink":"https:\/\/www.seekadventure.net\/d\/26-california-deer-springs-trail-san-jacinto-mountain","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":"Reflection Canyon","TrailHeadLat":"37.25220","TrailHeadLong":"-110.97350","GuideTitle":"Reflection Canyon","GuideLink":"https:\/\/www.seekadventure.net\/d\/24-utah-photographing-reflection-canyon","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":"Reflection Canyon","TrailHeadLat":"37.25220","TrailHeadLong":"-110.97350","GuideTitle":"Reflection Canyon Backpacking Guide (Clever Hiker)","GuideLink":"https:\/\/www.cleverhiker.com\/blog\/reflection-canyon-backpacking-guide","GuideMediaType":"blog"},{"TrailHeadID":"8","TrailHeadName":"Big Pine Lakes - North Fork Trail","TrailHeadLat":"37.12820","TrailHeadLong":"-118.42770","GuideTitle":"North Fork to 2nd Lake Sierra Nevada in a Snow Storm","GuideLink":"https:\/\/www.seekadventure.net\/d\/18-california-north-fork-to-2nd-lake-sierra-nevada-in-a-snow-storm","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"8","TrailHeadName":"Big Pine Lakes - North Fork Trail","TrailHeadLat":"37.12820","TrailHeadLong":"-118.42770","GuideTitle":"Hiking To Big Pine Lakes via The North Fork Trail (Trail to Peak)","GuideLink":"https:\/\/trailtopeak.com\/2017\/07\/09\/hiking-to-big-pine-lakes-via-the-north-fork-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"9","TrailHeadName":"Fish Creek Wash Anza Borrego","TrailHeadLat":"33.03872","TrailHeadLong":"-116.09941","GuideTitle":"Jeeping in Fish Creek Wash Anza Borrego","GuideLink":"https:\/\/www.seekadventure.net\/d\/99-jeeping-in-fish-creek-wash-anza-borrego","GuideMediaType":"SeekAdventure"}]';

myFunction(response);

var markers2 = new Array();


function myFunction(response) {
  var arr = JSON.parse(response);
  var i;
  var localTrailHeadID;
  var trailHeadCounter = 0;
  var TrailHeadObject;
  var lastTrailHeadID = 0;

  //set array conts all to zero
  var seekAdventureCount;
  var blogsCount;
  var youtubeCount;

  var j = 0;


  //for each row returned by mySQL
  for (i = 0; i < arr.length; i++) {
    localTrailHeadID = arr[i].TrailHeadID;

    //if previuse trailhead is the same as the current trail head get info and add to correct array
    if (localTrailHeadID == lastTrailHeadID) {
      if (arr[i].GuideMediaType == "SeekAdventure") {
        TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideTitle;
        console.log(arr[i].GuideTitle);
        seekAdventureCount = seekAdventureCount + 1;
        TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideLink;
        seekAdventureCount = seekAdventureCount + 1;
      }
      if (arr[i].GuideMediaType == "blog") {
        TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideTitle;
        console.log(arr[i].GuideTitle);
        blogsCount = blogsCount + 1;
        TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideLink;
        blogsCount = blogsCount + 1;
      }
      if (arr[i].GuideMediaType == "YouTube") {
        TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideTitle;
        console.log(arr[i].GuideTitle);
        youtubeCount = youtubeCount + 1;
        TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideLink;
        youtubeCount = youtubeCount + 1;
      }

    }

    //create new object and then add guide to correct array
    else {

      //add object to array of markers except on first round
      if (j == 0) {
        j = j + 1;
      } else {
        markers1[trailHeadCounter] = TrailHeadObject;
        console.log(trailHeadCounter);

        trailHeadCounter = trailHeadCounter + 1;
      }

      //create new trailhead object
      TrailHeadObject = new Object();

      //set array counters to zero
      var seekAdventureCount = 0;
      var blogsCount = 0;
      var youtubeCount = 0;

      //set name lat and long
      TrailHeadObject.name = arr[i].TrailHeadName;
      console.log(arr[i].TrailHeadName);
      TrailHeadObject.lat = arr[i].TrailHeadLat;
      TrailHeadObject.long = arr[i].TrailHeadLong;

      //set TrailHeadObject Guide arrays to empty
      TrailHeadObject.seekAdventureGuideList = [];
      TrailHeadObject.blogGuideList = [];
      TrailHeadObject.youTubegGuideList = [];

      //Add trail Guide
      //check first guide media type and add to correct Array
      if (arr[i].GuideMediaType == "SeekAdventure") {
        TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideTitle;
        console.log(arr[i].GuideTitle);
        seekAdventureCount = seekAdventureCount + 1;
        TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideLink;
        seekAdventureCount = seekAdventureCount + 1;
      }
      if (arr[i].GuideMediaType == "blog") {
        TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideTitle;
        console.log(arr[i].GuideTitle);
        blogsCount = blogsCount + 1;
        TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideLink;
        blogsCount = blogsCount + 1;
      }
      if (arr[i].GuideMediaType == "YouTube") {
        TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideTitle;
        console.log(arr[i].GuideTitle);
        youtubeCount = youtubeCount + 1;
        TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideLink;
        youtubeCount = youtubeCount + 1;
      }

    } // end else statement

    //set last trailhead ID
    lastTrailHeadID = localTrailHeadID;
  } //end for Loop
} //end my function

//Proceses JSON Info and build Objects and place into markers1 arrray

///////////////////////////////
//add Hike Objects to Array////
///////////////////////////////
/**
 * Function to init map
 */

// Before we go looking for the passed parameters, set some defaults
// in case there are no parameters
var id;
var index = -1;

//set initial map values
var lat = 40.534900;
var lng = -101.343789;
var zoom = 4;

// If there are any parameters at eh end of the URL, they will be in  location.search
// looking something like  "?marker=3"

// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);

// split the rest at each "&" character to give a list of  "argname=value"  pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
  // break each pair at the first "=" to obtain the argname and value
  var pos = pairs[i].indexOf("=");
  var argname = pairs[i].substring(0, pos).toLowerCase();
  var value = pairs[i].substring(pos + 1).toLowerCase();

  // process each possible argname  -  use unescape() if theres any chance of spaces
  if (argname == "id") {
    id = unescape(value);
  }
  if (argname == "marker") {
    index = parseFloat(value);
  }
  if (argname == "lat") {
    lat = parseFloat(value);
  }
  if (argname == "lng") {
    lng = parseFloat(value);
  }
  if (argname == "zoom") {
    zoom = parseInt(value);
  }
  if (argname == "type") {
    // from the v3 documentation 8/24/2010
    // HYBRID This map type displays a transparent layer of major streets on satellite images. 
    // ROADMAP This map type displays a normal street map. 
    // SATELLITE This map type displays satellite images. 
    // TERRAIN This map type displays maps with physical features such as terrain and vegetation. 
    if (value == "m") {
      maptype = google.maps.MapTypeId.ROADMAP;
    }
    if (value == "k") {
      maptype = google.maps.MapTypeId.SATELLITE;
    }
    if (value == "h") {
      maptype = google.maps.MapTypeId.HYBRID;
    }
    if (value == "t") {
      maptype = google.maps.MapTypeId.TERRAIN;
    }
  }
}

function makeLink() {
  var mapinfo = "lat=" + map.getCenter().lat().toFixed(6) +
    "&lng=" + map.getCenter().lng().toFixed(6) +
    "&zoom=" + map.getZoom() +
    "&type=" + MapTypeId2UrlValue(map.getMapTypeId());
  if (lastmarker) {
    var a = "https://www.seekadventure.net/adventureMap.html?id=" + lastmarker.id + "&" + mapinfo;
    var b = "https://www.seekadventure.net/adventureMap.html?marker=" + lastmarker.index + "&" + mapinfo;
  } else {
    var a = "https://www.seekadventure.net/adventureMap.html?" + mapinfo;
    var b = a;
  }

  document.getElementById("idlink").innerHTML = '<a href="' + a + '" id=url target=_new>Share Current Map View</a>';
}

function MapTypeId2UrlValue(maptype) {
  var urlValue = 'm';
  switch (maptype) {
    case google.maps.MapTypeId.HYBRID:
      urlValue = 'h';
      break;
    case google.maps.MapTypeId.SATELLITE:
      urlValue = 'k';
      break;
    case google.maps.MapTypeId.TERRAIN:
      urlValue = 't';
      break;
    default:
    case google.maps.MapTypeId.ROADMAP:
      urlValue = 'm';
      break;
  }
  return urlValue;
}
//----------------------------------------------------------
//initialize map 
function initialize() {
  var center = new google.maps.LatLng(lat, lng);
  var mapOptions = {
    zoom: zoom,
    center: center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  for (i = 0; i < markers1.length; i++) {
    console.log("inside new google map");
    console.log(markers1[i].name);
    addMarker(markers1[i]);
  }

  infowindow = new google.maps.InfoWindow({
    content: ''
  });

  // Make the link the first time when the page opens
  lastmarker = null;
  makeLink();

  // Make the link again whenever the map changes
  google.maps.event.addListener(map, 'maptypeid_changed', makeLink);
  google.maps.event.addListener(map, 'center_changed', makeLink);
  google.maps.event.addListener(map, 'bounds_changed', makeLink);
  google.maps.event.addListener(map, 'zoom_changed', makeLink);

  google.maps.event.addListener(map, 'click', function() {
    lastmarker = null;
    makeLink();
    infowindow.close();
  });
}

/**
 * Function to add marker to map
 */

function addMarker(marker) {
  var category = marker.type;
  var title = marker.name;
  var pos = new google.maps.LatLng(marker.lat, marker.long);
  var content = BuildBubbleHTML(marker);

  marker1 = new google.maps.Marker({
    title: title,
    position: pos,
    category: category,
    map: map
  });

  gmarkers1.push(marker1);

  // Marker click listener
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
    return function() {
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
      //map.setZoom(15);
    }
  })(marker1, content));
}

/////////////////////////
///Functions For Links///
/////////////////////////

//put pop up bubble html together 
function BuildBubbleHTML(hike) {
  html = "";
  html = html + '<h6>' + hike.name + '</h6>';
  console.log(hike);
  //If Seek Adventure Links Exist
  if (hike.seekAdventureGuideList.length > 0) {
    seekAdventureHTML = '<p>Seek Adventure Links</p>';
    seekAdventureHTML = seekAdventureHTML + '<ul>'
    var i;
    for (i = 0; i < hike.seekAdventureGuideList.length; i += 2) {
      seekAdventureHTML = seekAdventureHTML + '<li>';
      seekAdventureHTML = seekAdventureHTML + '<a href="' + hike.seekAdventureGuideList[i + 1] + '"target="_blank">';
      seekAdventureHTML = seekAdventureHTML + hike.seekAdventureGuideList[i] + '</a></li>';
    }
    seekAdventureHTML = seekAdventureHTML + '</ul>';
    html = html + seekAdventureHTML;
  }

  //If Blog Links Exist
  if (hike.blogGuideList.length > 0) {
    blogHTML = '<p>Blog Links</p>';
    blogHTML = blogHTML + '<ul>'
    var i;
    for (i = 0; i < hike.blogGuideList.length; i += 2) {
      blogHTML = blogHTML + '<li>';
      blogHTML = blogHTML + '<a href="' + hike.blogGuideList[i + 1] + '""target="_blank">';
      blogHTML = blogHTML + hike.blogGuideList[i] + '</a></li>';
    }
    blogHTML = blogHTML + '</ul>';
    html = html + blogHTML;
  }
  return html;
};

html,
body,
#map-canvas {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize" async defer></script>
<div id="idlink" style="display:none"></div>

这篇关于从JSON构建的对象数组未显示在我的Google地图上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆