2012-06-15 34 views
8

Me preguntaba si es posible que Google tenga una función para ver diferentes marcadores en diferentes niveles de acercamiento.Google Maps API v3 - Diferentes marcadores/etiquetas en diferentes niveles de zoom

Por ejemplo, el nivel de zoom 1, quiero un marcador sobre China con la etiqueta que dice "5". Y a medida que el usuario amplía, digamos en el nivel de zoom 4, quiero que el marcador y la etiqueta anterior desaparezcan. Y quiero tener 5 nuevos marcadores/etiquetas, cada uno en una ciudad diferente en China, todos diciendo "1". Por lo tanto, China dirá un número y todas las ciudades en China dirán números que suman al número de China.

El concepto clave que estoy tratando de averiguar aquí es cómo ocultar los marcadores y etiquetas basadas en niveles de zoom. Una limitación para mí es que actualmente vivo en China, donde Google está censurado, por lo que muchos documentos en línea me son censurados, incluida la documentación de Google.

Aquí está mi código hasta ahora

<!DOCTYPE html> 
<html> 
    <head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
    <title>TM China</title> 
    <style type="text/css"> 
     html, body, #map_canvas { margin: 0; padding: 0; height: 100% } 
    .labels { 
    color: red; 
    background-color: white; 
    font-family: "Lucida Grande", "Arial", sans-serif; 
    font-size: 10px; 
    font-weight: bold; 
    text-align: center; 
    width: 60px;  
    border: 2px solid black; 
    white-space: nowrap; 
    } 
    </style> 
    <script type="text/javascript" 
     src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDV0lcdK7C2GHbQAmdkBID70Uppuf-D030&sensor=true"> 
    </script> 
    <script type="text/javascript"> 

    eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('7 m(a){2.3=a;2.8=V.1E("1u");2.8.4.C="I: 1m; J: 1g;";2.k=V.1E("1u");2.k.4.C=2.8.4.C}m.l=E 6.5.22();m.l.1Y=7(){n c=2;n h=t;n f=t;n j;n b;n d,K;n i;n g=7(e){p(e.1v){e.1v()}e.2b=u;p(e.1t){e.1t()}};2.1s().24.G(2.8);2.1s().20.G(2.k);2.11=[6.5.9.w(V,"1o",7(a){p(f){a.s=j;i=u;6.5.9.r(c.3,"1n",a)}h=t;6.5.9.r(c.3,"1o",a)}),6.5.9.o(c.3.1P(),"1N",7(a){p(h&&c.3.1M()){a.s=E 6.5.1J(a.s.U()-d,a.s.T()-K);j=a.s;p(f){6.5.9.r(c.3,"1i",a)}F{d=a.s.U()-c.3.Z().U();K=a.s.T()-c.3.Z().T();6.5.9.r(c.3,"1e",a)}}}),6.5.9.w(2.k,"1d",7(e){c.k.4.1c="2i";6.5.9.r(c.3,"1d",e)}),6.5.9.w(2.k,"1D",7(e){c.k.4.1c=c.3.2g();6.5.9.r(c.3,"1D",e)}),6.5.9.w(2.k,"1C",7(e){p(i){i=t}F{g(e);6.5.9.r(c.3,"1C",e)}}),6.5.9.w(2.k,"1A",7(e){g(e);6.5.9.r(c.3,"1A",e)}),6.5.9.w(2.k,"1z",7(e){h=u;f=t;d=0;K=0;g(e);6.5.9.r(c.3,"1z",e)}),6.5.9.o(2.3,"1e",7(a){f=u;b=c.3.1b()}),6.5.9.o(2.3,"1i",7(a){c.3.O(a.s);c.3.D(2a)}),6.5.9.o(2.3,"1n",7(a){f=t;c.3.D(b)}),6.5.9.o(2.3,"29",7(){c.O()}),6.5.9.o(2.3,"28",7(){c.D()}),6.5.9.o(2.3,"27",7(){c.N()}),6.5.9.o(2.3,"26",7(){c.N()}),6.5.9.o(2.3,"25",7(){c.16()}),6.5.9.o(2.3,"23",7(){c.15()}),6.5.9.o(2.3,"21",7(){c.13()}),6.5.9.o(2.3,"1Z",7(){c.L()}),6.5.9.o(2.3,"1X",7(){c.L()})]};m.l.1W=7(){n i;2.8.1r.1q(2.8);2.k.1r.1q(2.k);1p(i=0;i<2.11.1V;i++){6.5.9.1U(2.11[i])}};m.l.1T=7(){2.15();2.16();2.L()};m.l.15=7(){n a=2.3.z("Y");p(H a.1S==="P"){2.8.W=a;2.k.W=2.8.W}F{2.8.G(a);a=a.1R(u);2.k.G(a)}};m.l.16=7(){2.k.1Q=2.3.1O()||""};m.l.L=7(){n i,q;2.8.S=2.3.z("R");2.k.S=2.8.S;2.8.4.C="";2.k.4.C="";q=2.3.z("q");1p(i 1L q){p(q.1K(i)){2.8.4[i]=q[i];2.k.4[i]=q[i]}}2.1l()};m.l.1l=7(){2.8.4.I="1m";2.8.4.J="1g";p(H 2.8.4.B!=="P"){2.8.4.1k="1j(B="+(2.8.4.B*1I)+")"}2.k.4.I=2.8.4.I;2.k.4.J=2.8.4.J;2.k.4.B=0.1H;2.k.4.1k="1j(B=1)";2.13();2.O();2.N()};m.l.13=7(){n a=2.3.z("X");2.8.4.1h=-a.x+"v";2.8.4.1f=-a.y+"v";2.k.4.1h=-a.x+"v";2.k.4.1f=-a.y+"v"};m.l.O=7(){n a=2.1G().1F(2.3.Z());2.8.4.12=a.x+"v";2.8.4.M=a.y+"v";2.k.4.12=2.8.4.12;2.k.4.M=2.8.4.M;2.D()};m.l.D=7(){n a=(2.3.z("14")?-1:+1);p(H 2.3.1b()==="P"){2.8.4.A=2h(2.8.4.M,10)+a;2.k.4.A=2.8.4.A}F{2.8.4.A=2.3.1b()+a;2.k.4.A=2.8.4.A}};m.l.N=7(){p(2.3.z("1a")){2.8.4.Q=2.3.2f()?"2e":"1B"}F{2.8.4.Q="1B"}2.k.4.Q=2.8.4.Q};7 19(a){a=a||{};a.Y=a.Y||"";a.X=a.X||E 6.5.2d(0,0);a.R=a.R||"2c";a.q=a.q||{};a.14=a.14||t;p(H a.1a==="P"){a.1a=u}2.1y=E m(2);6.5.18.1x(2,1w)}19.l=E 6.5.18();19.l.17=7(a){6.5.18.l.17.1x(2,1w);2.1y.17(a)};',62,143,'||this|marker_|style|maps|google|function|labelDiv_|event|||||||||||eventDiv_|prototype|MarkerLabel_|var|addListener|if|labelStyle|trigger|latLng|false|true|px|addDomListener|||get|zIndex|opacity|cssText|setZIndex|new|else|appendChild|typeof|position|overflow|cLngOffset|setStyles|top|setVisible|setPosition|undefined|display|labelClass|className|lng|lat|document|innerHTML|labelAnchor|labelContent|getPosition||listeners_|left|setAnchor|labelInBackground|setContent|setTitle|setMap|Marker|MarkerWithLabel|labelVisible|getZIndex|cursor|mouseover|dragstart|marginTop|hidden|marginLeft|drag|alpha|filter|setMandatoryStyles|absolute|dragend|mouseup|for|removeChild|parentNode|getPanes|stopPropagation|div|preventDefault|arguments|apply|label|mousedown|dblclick|none|click|mouseout|createElement|fromLatLngToDivPixel|getProjection|01|100|LatLng|hasOwnProperty|in|getDraggable|mousemove|getTitle|getMap|title|cloneNode|nodeType|draw|removeListener|length|onRemove|labelstyle_changed|onAdd|labelclass_changed|overlayMouseTarget|labelanchor_changed|OverlayView|labelcontent_changed|overlayImage|title_changed|labelvisible_changed|visible_changed|zindex_changed|position_changed|1000000|cancelBubble|markerLabels|Point|block|getVisible|getCursor|parseInt|pointer'.split('|'),0,{})) 
    var map; 
    var mapOptions = { center: new google.maps.LatLng(35, 105), zoom: 3, 
     mapTypeId: google.maps.MapTypeId.ROADMAP }; 



    var locations = [ 
        ['Hong Kong', 22.39, 114.10, 1885], 
        ['Shanghai', 31.232, 121.47, 5885], 
        ['Beijing', 39.88, 116.40, 6426], 
        ['Guangzhou', 23.129, 113.264, 4067], 
        ['Shenzhen', 22.54, 114.05, 3089], 
        ['Hangzhou', 30.27, 120.15, 954] 
        ]; 

    var infowindow = new google.maps.InfoWindow(); 

    var i; 
    /* 
    for (i = 0; i < locations.length; i++) { 
     marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
      map: map 
     }); 

     google.maps.event.addListener(marker, 'click', (function(marker, i) { 
      return function() { 
      infowindow.setContent(locations[i][0]); 
      infowindow.open(map, marker); 
      } 
     })(marker, i)); 
     } */ 

    function myMarker(options) { 
     if(!options.labelAnchor) { 
      options.labelAnchor = new google.maps.Point(30, 50); 
     } 
     if(!options.labelClass) { 
      options.labelClass = "labels"; 
     } 
     options.map = map; 

     return new MarkerWithLabel(options); 
     } 

    function initialize() { 
     map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 
     for (i = 0; i < locations.length; i++) { 
     var marker = new MarkerWithLabel({ 
      position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
      draggable: false, 
      map: map, 
      labelContent: locations[i][3], 
      labelAnchor: new google.maps.Point(30, 0), 
      labelClass: "labels", // the CSS class for the label 
      labelStyle: {opacity: 0.75} 

     }); 
     } 
     /* 
     var marker2 = new myMarker({ 
      position: new google.maps.LatLng(20,20), 
      draggable: true, 
      labelContent: "second" 
      }); 
*/ 
     } 
    google.maps.event.addDomListener(window, 'load', initialize); 
    </script> 
    </head> 
    <body onload="initialize()"> 
    <div id="map_canvas" style="width:85%; height:85%"></div> 
    <script type="text/javascript"> 
    </script> 
    </body> 
</html> 

EDITAR

he estado tratando de experimentar con el MarkerManager, pero no puedo conseguir los marcadores para crear con éxito en diferentes niveles de zoom .

En primer lugar, he cambiado de nivel de zoom predeterminado a 1, y luego cambió mi código a lo que se muestra a continuación.

function initialize() { 
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 
    /* for (i = 0; i < locations.length; i++) { 
    var marker = new MarkerWithLabel({ 
     position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
     draggable: false, 
     map: map, 
     labelContent: locations[i][3], 
     labelAnchor: new google.maps.Point(30, 0), 
     labelClass: "labels", // the CSS class for the label 
     labelStyle: {opacity: 0.75} 

    }); 
    } */ 
    var listener = google.maps.event.addListener(map, 'bounds_changed', function(){ 
     setupMarkers(); 
     google.maps.event.removeListener(listener); 
    }); 
    } 

function createCityMarkers() { 


    for (i = 0; i < locations.length; i++) { 
     var marker = new MarkerWithLabel({ 
      position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
      draggable: false, 
      map: map, 
      labelContent: locations[i][3], 
      labelAnchor: new google.maps.Point(30, 0), 
      labelClass: "labels", // the CSS class for the label 
      labelStyle: {opacity: 0.75} 

     }); 
     } 
} 

function setupMarkers() { 
    mgr = new MarkerManager(map); 

    google.maps.event.addListener(mgr, 'loaded', function(){ 
      mgr.addMarkers(createCityMarkers(), 4); 

      mgr.refresh(); 
     }); 
} 

También he intentado aplicar el código fuente de este enlace, pero nada está funcionando. Y cuando copio el código fuente directamente en mi computadora y reemplazo todos los íconos con marcadores, los marcadores aún no aparecen. Parece que no puedo imaginar cómo hacer que aparezcan los marcadores usando el marcador Manager. http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/examples/weather_map.html

+0

También he intentado utilizar un procedimiento por lotes para crear las etiquetas cuando hice acercamiento, pero eso no funciona para mí. – krikara

+0

Estoy hasta el punto en que solo tengo un mapa, un marcador y agrego 1 marcador. Esto ni siquiera funciona ... – krikara

Respuesta

9

La verdadera razón por la que mi programa estaba fallando era debido al administrador de marcadores, que no funciona con mis marcadores con etiquetas.

Hubo un enfoque mucho más simple, sin embargo, para satisfacer mis necesidades.

function initialize() { 
     map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 

     getMarkers(); 
     google.maps.event.addListener(map,'zoom_changed',function() { 
      if (map.getZoom() >= 3) showMarkers(); 
      if (map.getZoom() <= 2) eraseMarkers(); 

      }); 

    } 

    function eraseMarkers() { 
     for (i = 0; i < locations.length; i++) { 
      marker[i].setVisible(false); 
     } 

     } 

    function showMarkers() { 
     for (i = 0; i < locations.length; i++) { 
      marker[i].setVisible(true); 
     } 

     } 

    function getMarkers() { 
     for (i = 0; i < locations.length; i++) { 
      marker[i] = new MarkerWithLabel({ 
       position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
       draggable: false, 
       map: map, 
       labelContent: locations[i][3], 
       labelAnchor: new google.maps.Point(30, 0), 
       labelClass: "labels", // the CSS class for the label 
       labelStyle: {opacity: 0.75} 
      }); 


      } 
     eraseMarkers(); 
     } 
1

Parece que lo que estás tratando de hacer se llama Marker Clustering.

Aquí hay un montón de exmamples oficial de Google https://developers.google.com/maps/articles/toomanymarkers escritos en Javascript nativo

http://gmap3.net/examples/clustering.html - usando la biblioteca jQuery.

Espero que esto te ayude.

+0

En el primer enlace dado, la función que necesito usar se llama Marker Manager. La diferencia entre su uso y mi uso es que convierten a cada marcador en un ícono, mientras que yo estoy usando un marcador con una etiqueta. El problema que tengo es que no puedo hacer que Marker Manager agregue/elimine marcadores en función del nivel de zoom, incluso cuando prácticamente copié el código y eliminé todas las cosas relacionadas con el ícono. Hago mis propios marcadores e intento usar la función mgr.addMarker() pero no obtengo ningún resultado. – krikara

+0

Bajo la forma conceptual de crear agrupaciones de Marcadores con Marcadores/Iconos, pero cada vez que intento aplicarlo a mi propio código, no obtengo ningún resultado.Creo que tiene algo que ver con la sintaxis, pero no sé qué es exactamente lo que está mal, ya que todo lo que cambié del ejemplo de Google fue addMarkers() para addMarker() y también creé mi propio marcador. Otra cosa que me tiene perplejo es que la página Marker Manager especifica que addMarker (s) tiene 3 parámetros, pero la fuente de google usa solo 2. A pesar de eso, he intentado y mezclado tantas variaciones del código y simplemente estoy mirando estupefacto a mi pantalla – krikara

+0

En realidad, estoy casi seguro de que me di cuenta de lo que estaba mal. Estaba usando Marker Manager suministrado por Google API v3, sin embargo, edité los marcadores para permitir etiquetas. Y ahora Marker Manager no es compatible con mi programa. – krikara