在一个页面中无法使用google map api显示多个地理位置

时间:2014-03-30 21:45:43

标签: javascript html html5 image google-maps-api-3

我使用googleapi在一个页面中显示多个地方的geolocation,但这是不可能的。

我初始化一个变量来计算地图:

var countmaps=1;

我在循环中执行以下操作(对于我想要显示的每个地图):

首先,我从xml文件中获取经度和纬度。这是有效的:

var lat= latitude[0].childNodes[0].nodeValue;
var lon= longitude[0].childNodes[0].nodeValue;

在此之后,我创建一个新的段落元素来保存每个地图:

var newmap=document.createElement('p');

元素的ID是第一个地图的map1,第二个地图的map2等。

newmap.id="maps" + countmaps;

然后,我将id保存在变量中:

var getid= "maps" + countmaps;

我将新元素追加到名为section的div:

section.appendChild(newmap);

到目前为止一切正常。 然后我定义了显示地图的功能。我从w3schools获取了它们:

    function getLocation()
      {
            if (navigator.geolocation)
        {
        navigator.geolocation.getCurrentPosition(showPosition,showError);
        }
      else{x.innerHTML="Geolocation is not supported by this browser.";//not important
      }
      }

    function showPosition()
      {
      var latlon=lat+","+lon;

      var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
      +latlon+"&zoom=14&size=400x300&sensor=false";
    //i get element with id map1 in the first loop, map2 in the second etc in the below
      document.getElementById(getid).innerHTML="<img src='"+img_url+"'>";
      }

    function showError(error)
      {
      switch(error.code) 
        {
        case error.PERMISSION_DENIED:
          document.getElementById(getid).innerHTML="MAP Not Available"
          break;
        case error.POSITION_UNAVAILABLE:
         document.getElementById(getid).innerHTML="MAP Not Available"
          break;
        case error.TIMEOUT:
          document.getElementById(getid).innerHTML="MAP Not Available"
          break;
        case error.UNKNOWN_ERROR:
          document.getElementById(getid).innerHTML="MAP Not Available"
          break;
        }


 }

最后,我调用了getlocation函数并增加了元素id的计数器。

getLocation();
 countmaps++;

在大多数情况下,我只获得了最后一张地图。 你能解释一下这种行为吗?

1 个答案:

答案 0 :(得分:2)

您不需要多次调用地理位置服务,每次都会返回相同的结果。

相关问题