AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79554127
Accepted
Salvador
Salvador
Asked: 2025-04-04 06:28:41 +0800 CST2025-04-04 06:28:41 +0800 CST 2025-04-04 06:28:41 +0800 CST

Como mostrar coordenadas de retícula ao longo dos eixos no folheto

  • 772

É possível adicionar marcas de escala de retícula e coordenadas ao redor das bordas de um leafletgráfico? Algo como a captura de tela abaixo, mas com valores de lon/lat incluídos? Procurei online, mas não encontrei uma solução.

map <- leaflet() %>%
  addTiles() %>%
  setView(lng = -118.88, lat = 38.1341, zoom = 8) #|>
  #addCoordinates()
map

insira a descrição da imagem aqui

  • 1 1 respostas
  • 57 Views

1 respostas

  • Voted
  1. Best Answer
    2025-04-04T17:17:35+08:002025-04-04T17:17:35+08:00

    Combinei a solução compass com o plugin autograticule .

    1. Copie o código do autograticule
    2. Ajuste conforme necessário
    3. Adicione-o ao mapa do folheto usandohtmltools fora

    Ajustes

    1 - você pode especificar a distância das linhas de retícula dependendo do nível de zoom. Basta ajustar a configuração if-else lineOffsetno código abaixo.

    2 - no final do código, adicionei um pouco de css para ajustar o estilo dos rótulos, ajuste o tamanho da fonte/cor ao seu gosto.

    3 - os rótulos de retícula são mostrados dentro do mapa de folhetos, portanto, tive que garantir que a IU existente não obstruísse os rótulos. Então, os rótulos de Latitude são deslocados da borda esquerda em 4%, a Longitude 5% da parte inferior. Ajuste isso conforme necessário.

    Código

    
    library(leaflet)
    library(htmltools) 
    
    map <- leaflet() %>%
      addTiles() %>%
      setView(lng = -118.88, lat = 38.1341, zoom = 8) %>%
      addScaleBar(position = "bottomleft", options = scaleBarOptions(maxWidth = 100, metric = TRUE, imperial = FALSE)) %>%
      addControl(HTML('
    <div style="width: 90px;height: 90px;">
        <img src="https://clipart-library.com/images/rTnRjnAGc.png" style="width: 100%; width: 100%; opacity: 0.7;">
    </div>'), position = "topright", className = "leaflet-control-nobg") %>%
      htmlwidgets::onRender("
        function(el, x) {
          // Store reference to map
          var map = this;
          
          // Define the AutoGraticule plugin directly
          L.AutoGraticule = L.LayerGroup.extend({
            options: {
              redraw: 'move',
              minDistance: 20
            },
            
            initialize: function(options) {
              L.LayerGroup.prototype.initialize.call(this);
              L.Util.setOptions(this, options);
              this._layers = {};
              this._zoom = -1;
            },
            
            onAdd: function(map) {
              this._map = map;
              map.on('viewreset ' + this.options.redraw, this._reset, this);
              this._reset();
            },
            
            onRemove: function(map) {
              map.off('viewreset ' + this.options.redraw, this._reset, this);
              this.clearLayers();
            },
            
            _reset: function() {
              this.clearLayers();
              
              var currentZoom = this._map.getZoom(); // 0 completely zoomed out, 18-20 completely zoomed in
              var bounds = this._map.getBounds();
              var sw = bounds.getSouthWest();
              var ne = bounds.getNorthEast();
              
              // Calculate a better position for longitude labels (5% from bottom of map)
              var labelLat = sw.lat + (ne.lat - sw.lat) * 0.05;
              
              // Determine line offset of graticules based on zoom level using a formula
              //var lineOffset = Math.round(40 * Math.pow(0.6, currentZoom) * 100) / 100;
              // or manually
              var lineOffset;
              if (currentZoom <= 2) {
                lineOffset = 30; 
              } else if (currentZoom <= 4) {
                lineOffset = 10; 
              } else if (currentZoom <= 6) {
                lineOffset = 5;  
              } else if (currentZoom <= 8) {
                lineOffset = 2;  
              } else if (currentZoom <= 10) {
                lineOffset = 1; 
              } else if (currentZoom <= 12) {
                lineOffset = 0.5; 
              }else {
                lineOffset = 0.1; 
              }
              
              console.log('Current Zoom: ', currentZoom, ', LineOffset: ', lineOffset);
             
              
              // longitude lines
              for (var lng = Math.floor(sw.lng / lineOffset) * lineOffset; 
                   lng <= Math.ceil(ne.lng / lineOffset) * lineOffset; 
                   lng += lineOffset) {
                
                var roundedLng = Math.round(lng * 100) / 100; // Round to 2 decimal places
                var line = L.polyline([[sw.lat, roundedLng], [ne.lat, roundedLng]], 
                                      {color: '#888', weight: 1, opacity: 0.5});
                this.addLayer(line);
                
                if (Math.abs(roundedLng) > 0.001) { // Avoid adding label at exactly 0
                  // Format label based on line offset - show decimals only when needed
                  var lngLabel = roundedLng.toFixed(lineOffset < 1 ? 1 : 0) + '°';
                  
                  var lngMarker = L.marker([labelLat, roundedLng], {
                    icon: L.divIcon({
                      className: 'leaflet-graticule-label',
                      html: lngLabel,
                      iconSize: [0, 0],
                      iconAnchor: [0, 0]
                    })
                  });
                  this.addLayer(lngMarker);
                }
              }
              
              // Draw latitude lines
              for (var lat = Math.floor(sw.lat / lineOffset) * lineOffset; 
                   lat <= Math.ceil(ne.lat / lineOffset) * lineOffset; 
                   lat += lineOffset) {
                
                var roundedLat = Math.round(lat * 100) / 100; // Round to 2 decimal places
                var line = L.polyline([[roundedLat, sw.lng], [roundedLat, ne.lng]], 
                                      {color: '#888', weight: 1, opacity: 0.5});
                this.addLayer(line);
                
                if (Math.abs(roundedLat) > 0.001) { // Avoid adding label at exactly 0
                  // Format label based on line offset - show decimals only when needed
                  var latLabel = roundedLat.toFixed(lineOffset < 1 ? 1 : 0) + '°';
                                                                                    // adjust left offset
                  var latMarker = L.marker([roundedLat, sw.lng + (ne.lng - sw.lng) * 0.04], {
                    icon: L.divIcon({
                      className: 'leaflet-graticule-label',
                      html: latLabel,
                      iconSize: [0, 0],
                      iconAnchor: [0, 0]
                    })
                  });
                  this.addLayer(latMarker);
                }
              }
              
              // Add some CSS for the labels
              if (!document.getElementById('graticule-style')) {
                var style = document.createElement('style');
                style.id = 'graticule-style';
                style.innerHTML = '.leaflet-graticule-label { color: black; font-weight: bold; font-size: 14px; white-space: nowrap; text-shadow: 1px 1px 1px #fff, -1px 1px 1px #fff, 1px -1px 1px #fff, -1px -1px 1px #fff; }';
                document.head.appendChild(style);
              }
            }
          });
          
          L.autoGraticule = function(options) {
            return new L.AutoGraticule(options);
          };
          
          // Add the graticule to the map
          var graticule = L.autoGraticule().addTo(map);
        }
      ")
    
    
    
    
    map <- htmlwidgets::prependContent(map, 
                                       tags$style(".leaflet-control-nobg { background: none !important; box-shadow: none !important; border: none !important; }")
    )
    
    map
    
    
    • 0

relate perguntas

  • Adicionar número de série para atividade de cópia ao blob

  • A fonte dinâmica do empacotador duplica artefatos

  • Selecione linhas por grupo com 1s consecutivos

  • Lista de chamada de API de gráfico subscritoSkus estados Privilégios insuficientes enquanto os privilégios são concedidos

  • Função para criar DFs separados com base no valor da coluna

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve