Google Maps V3 API - 从xml文件中拉取类别的中心 [英] Google Maps V3 API - Center on a category pulling from xml file

查看:86
本文介绍了Google Maps V3 API - 从xml文件中拉取类别的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自Geocodezip的此示例



地图上的标记根据所选类别的不同而不同。我希望他们能够自动将标记集中在标记的类别上,但我很难使其发挥作用。

我在这里和其他地方找到的所有fitbounds示例的问题是,它们需要在JavaScript中定义标记,而我的存在从XML文件导入。我不确定接下来要尝试什么。

脚本:

 < script type =text /的javascript> 
//<![CDATA [
//此变量将收集最终放置在side_bar中的html
var side_bar_html =;

var gmarkers = [];
var gicons = [];
var map = null;

var infowindow = new google.maps.InfoWindow(
{
size:new google.maps.Size(150,50)
});


gicons [red] = new google.maps.MarkerImage(mapIcons / marker_red.png,
//此标记宽20像素,高34像素。
new google.maps.Size(20,34),
//此图片的来源为0,0。
new google.maps.Point(0,0),
//此图片的锚点位于9,34。
new google.maps.Point(9,34));
//标记大小表示为X的大小,Y
//图像的原点(0,0)位于图像左上角的
//。

//标记的起源,锚点位置和坐标
//沿X方向向右增加,在
//向下Y方向增加。

var iconImage = new google.maps.MarkerImage('mapIcons / marker_red.png',
//此标记宽20像素,高34像素。 maps.Size(20,34),
//此图片的原点为0,0。
new google.maps.Point(0,0),
//此图片为9,34。
new google.maps.Point(9,34));
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
//阴影图像在水平尺寸上较大
//位置和偏移量与主图像相同
new google.maps.Size(37,34),
new google.maps.Point(0,0),
new google.maps.Point(9,34));
//形状定义图标的可点击区域。
//该类型定义了HTML& lt; area& gt;元素'poly',其中
//将多边形描绘为一系列X,Y点。最后的
//坐标通过连接到第一个
//坐标来关闭poly。
var iconShape = {
coord:[9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19 ,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20 ,8,18,4,16,2,15,1,13,0],
类型:'poly'
};

函数getMarkerImage(iconColor){
if((typeof(iconColor)==undefined)||(iconColor == null)){
iconColor =red ;
}
if(!gicons [iconColor]){
gicons [iconColor] = new google.maps.MarkerImage(mapIcons / marker _+ iconColor +。png,
//此标记宽20像素,高34像素
new google.maps.Size(20,34),
//此图像的原点为0,0
new google.maps.Point(0,0),
//此图片的锚点位于6,20。
new google.maps.Point(9,34));
}
返回gicons [iconColor];

}

函数category2color(类别){
var color =red;
switch(category){
casetheatre:color =blue;
休息;
casegolf:color =green;
休息;
caseinfo:color =yellow;
休息;
default:color =red;
休息;
}
返回颜色;
}

gicons [theatre] = getMarkerImage(category2color(theatre));
gicons [golf] = getMarkerImage(category2color(golf));
gicons [info] = getMarkerImage(category2color(info));

//创建标记并设置事件窗口的函数
函数createMarker(latlng,name,html,category){
var contentString = html;
var marker = new google.maps.Marker({
位置:latlng,
图标:gicons [category],
shadow:iconShadow,
map:map,
title:name,
zIndex:Math.round(latlng.lat()* - 100000)<5
});
// ===将类别和名称信息存储为标记属性===
marker.mycategory = category;
marker.myname = name;
gmarkers.push(marker);

google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}

// ==显示特定类别的所有标记,并确保复选框被选中==
function show(category){
for(var如果(gmarkers [i] .mycategory == category){
gmarkers [i] .setVisible(true); i = 0; i< gmarkers.length; i ++){
if


==检查复选框==
document.getElementById(category +box)。checked = true;
}

// ==隐藏特定类别的所有标记,并确保复选框被清除==
function hide(category){
for(var如果(gmarkers [i] .mycategory ==类别){
gmarkers [i] .setVisible(false); i = 0; i< gmarkers.length; i ++){
if
}
}
// ==清除复选框==
document.getElementById(category +box)。checked = false;
// ==关闭信息窗口,以防它在我们刚刚隐藏的标记上打开
infowindow.close();


==一个复选框已被点击==
function boxclick(box,category){
if(box.checked){
显示(类别);
} else {
hide(category);
}
// ==重建侧边栏
makeSidebar();
}

函数myclick(i){
google.maps.event.trigger(gmarkers [i],click);
}


// ==重建侧边栏以匹配当前显示的标记==
函数makeSidebar(){
var html = ;
for(var i = 0; i if(gmarkers [i] .getVisible()){
html + ='< a href = javascript:myclick('+ i +')>'+ gmarkers [i] .myname +'< \ / a>< br>';
}
}
document.getElementById(side_bar)。innerHTML = html;
}

函数initialize(){
var myOptions = {
zoom:11,
center:new google.maps.LatLng(53.8363, - 3.0377),
mapTypeId:google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById(map),myOptions);

$ b google.maps.event.addListener(map,'click',function(){
infowindow.close();
});


$ b //读取数据
downloadUrl(categories.xml,function(doc){
var xml = xmlParse(doc);
var markers = xml.documentElement.getElementsByTagName(marker);

(var i = 0; i< markers.length; i ++){
//获取每个标记的属性
var lat = parseFloat(markers [i] .getAttribute(lat));
var lng = parseFloat(markers [i] .getAttribute(lng));
var point = new google.maps.LatLng(lat,lng);
var address = markers [i] .getAttribute(address);
var name = markers [i] .getAttribute (name);
var html =< b>+ name +< \ / b>< p>+ address;
var category = markers [i] .getAttribute (category);
//创建标记
var marker = createMarker(point,name,html,category);
}

// ==最初显示或隐藏类别==
show(剧院);
hide(高尔夫);
hide(info);
// ==创建初始侧边栏==
makeSidebar();
});
}

//此Javascript基于
//社区教会Javascript团队
// http://www.bisphamchurch.org提供的代码。 uk /
// http://econym.org.uk/gmap/
//从v2教程页面:
// http://econym.org.uk/gmap /example_categories.htm
//]]>


解决方案

要放大到最后一个显示类别,标记指向 google.maps.LatLngBounds 对象,然后调用 map.fitBounds ,以该对象作为参数。

  // ==显示特定类别的所有标记,并确保复选框被选中,缩放到此类别显示的标记== 
function show(category){
var bounds = new google.maps.LatLngBounds();
for(var i = 0; i< gmarkers.length; i ++){
if(gmarkers [i] .mycategory == category){
gmarkers [i] .setVisible(true) ;
bounds.extend(gmarkers [i] .getPosition());
}
}
map.fitBounds(bounds);
// ==检查复选框==
document.getElementById(category +box)。checked = true;
}

工作示例


I'm working with this example from Geocodezip

The markers on the map change depending on which category is selected. I would like them to automatically center on the category of markers but I'm having difficulty getting it to work.

The issue I'm having with all the fitbounds examples I've found on here and elsewhere is that they require the markers to be defined in the Javascript whereas mine are being imported from an XML file. I'm not sure what to try next.

The script:

<script type="text/javascript">
    //<![CDATA[
      // this variable will collect the html which will eventually be placed in the side_bar 
      var side_bar_html = ""; 

      var gmarkers = [];
      var gicons = [];
      var map = null;

var infowindow = new google.maps.InfoWindow(
  { 
    size: new google.maps.Size(150,50)
  });


gicons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(20, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 9,34.
      new google.maps.Point(9, 34));
  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.

  var iconImage = new google.maps.MarkerImage('mapIcons/marker_red.png',
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(20, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 9,34.
      new google.maps.Point(9, 34));
  var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 34),
      new google.maps.Point(0,0),
      new google.maps.Point(9, 34));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML &lt;area&gt; element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var iconShape = {
      coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
      type: 'poly'
  };

function getMarkerImage(iconColor) {
   if ((typeof(iconColor)=="undefined") || (iconColor==null)) { 
      iconColor = "red"; 
   }
   if (!gicons[iconColor]) {
      gicons[iconColor] = new google.maps.MarkerImage("mapIcons/marker_"+ iconColor +".png",
      // This marker is 20 pixels wide by 34 pixels tall.
      new google.maps.Size(20, 34),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is at 6,20.
      new google.maps.Point(9, 34));
   } 
   return gicons[iconColor];

}

function category2color(category) {
   var color = "red";
   switch(category) {
     case "theatre": color = "blue";
                break;
     case "golf":    color = "green";
                break;
     case "info":    color = "yellow";
                break;
     default:   color = "red";
                break;
   }
   return color;
}

      gicons["theatre"] = getMarkerImage(category2color("theatre"));
      gicons["golf"] = getMarkerImage(category2color("golf"));
      gicons["info"] = getMarkerImage(category2color("info"));

      // A function to create the marker and set up the event window
function createMarker(latlng,name,html,category) {
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        icon: gicons[category],
        shadow: iconShadow,
        map: map,
        title: name,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });
        // === Store the category and name info as a marker properties ===
        marker.mycategory = category;                                 
        marker.myname = name;
        gmarkers.push(marker);

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,marker);
        });
}

      // == shows all markers of a particular category, and ensures the checkbox is checked ==
      function show(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].setVisible(true);
          }
        }
        // == check the checkbox ==
        document.getElementById(category+"box").checked = true;
      }

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
      function hide(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].setVisible(false);
          }
        }
        // == clear the checkbox ==
        document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        infowindow.close();
      }

      // == a checkbox has been clicked ==
      function boxclick(box,category) {
        if (box.checked) {
          show(category);
        } else {
          hide(category);
        }
        // == rebuild the side bar
        makeSidebar();
      }

      function myclick(i) {
        google.maps.event.trigger(gmarkers[i],"click");
      }


      // == rebuilds the sidebar to match the markers currently displayed ==
      function makeSidebar() {
        var html = "";
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].getVisible()) {
            html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
          }
        }
        document.getElementById("side_bar").innerHTML = html;
      }

  function initialize() {
    var myOptions = {
      zoom: 11,
      center: new google.maps.LatLng(53.8363,-3.0377),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map"), myOptions);


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



      // Read the data
      downloadUrl("categories.xml", function(doc) {
  var xml = xmlParse(doc);
  var markers = xml.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {
          // obtain the attribues of each marker
          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var point = new google.maps.LatLng(lat,lng);
          var address = markers[i].getAttribute("address");
          var name = markers[i].getAttribute("name");
          var html = "<b>"+name+"<\/b><p>"+address;
          var category = markers[i].getAttribute("category");
          // create the marker
          var marker = createMarker(point,name,html,category);
        }

        // == show or hide the categories initially ==
        show("theatre");
        hide("golf");
        hide("info");
        // == create the initial sidebar ==
        makeSidebar();
      });
    }

    // This Javascript is based on code provided by the
    // Community Church Javascript Team
    // http://www.bisphamchurch.org.uk/   
    // http://econym.org.uk/gmap/
    // from the v2 tutorial page at:
    // http://econym.org.uk/gmap/example_categories.htm
    //]]>

解决方案

To zoom to the last "shown" category, add the markers to a google.maps.LatLngBounds object, then call map.fitBounds with that object as its argument.

// == shows all markers of a particular category, and ensures the checkbox is checked, zooms to the displayed markers of this category ==
function show(category) {
  var bounds = new google.maps.LatLngBounds();
  for (var i=0; i<gmarkers.length; i++) {
    if (gmarkers[i].mycategory == category) {
      gmarkers[i].setVisible(true);
      bounds.extend(gmarkers[i].getPosition());
    }
  }
  map.fitBounds(bounds);
  // == check the checkbox ==
  document.getElementById(category+"box").checked = true;
}

working example

这篇关于Google Maps V3 API - 从xml文件中拉取类别的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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