【问题标题】:get latitude & longitude as per address given for leaflet根据传单给定的地址获取纬度和经度
【发布时间】:2013-04-10 07:09:46
【问题描述】:

在我的项目中,我使用传单来显示点。

我正在从我的数据库中获取地址并希望显示该特定地址的点。

根据所提供的地址,我没有找到任何可以为我提供纬度和经度的信息。

谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript leaflet


    【解决方案1】:

    如果您想为此使用 OpenStreetmaps,您可以简单地发出请求(使用 jquery):

        $.get(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q='+address, function(data){
           console.log(data);
        });
    

    您将获得包含(不仅)纬度和经度的 JSON 对象。

    【讨论】:

    • 这是免费的吗?无限请求?
    【解决方案2】:

    没有额外插件的解决方案。只有 Leaflet 和纯 JavaScript。拖动标记或输入地址会为您提供坐标。如果您对 nominatim 请求有疑问,只需将 https 更改为 http。 在这里演示:http://yellowthailand.com/leafletgeo.html

    <html>
    <head>
    <title>Leaflet Address Lookup and Coordinates</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
    <style type="text/css">
    html, body { width:100%;padding:0;margin:0; }
    .container { width:95%;max-width:980px;padding:1% 2%;margin:0 auto }
    #lat, #lon { text-align:right }
    #map { width:100%;height:50%;padding:0;margin:0; }
    .address { cursor:pointer }
    .address:hover { color:#AA0000;text-decoration:underline }
    </style>
    </head>
    <body>
    <div class="container">
    
    <b>Coordinates</b>
    <form>
    <input type="text" name="lat" id="lat" size=12 value="">
    <input type="text" name="lon" id="lon" size=12 value="">
    </form>
    
    <b>Address Lookup</b>
    <div id="search">
    <input type="text" name="addr" value="" id="addr" size="58" />
    <button type="button" onclick="addr_search();">Search</button>
    <div id="results"></div>
    </div>
    
    <br />
    
    <div id="map"></div>
    
    </div>
    
    <script type="text/javascript">
    
    // New York
    var startlat = 40.75637123;
    var startlon = -73.98545321;
    
    var options = {
     center: [startlat, startlon],
     zoom: 9
    }
    
    document.getElementById('lat').value = startlat;
    document.getElementById('lon').value = startlon;
    
    var map = L.map('map', options);
    var nzoom = 12;
    
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {attribution: 'OSM'}).addTo(map);
    
    var myMarker = L.marker([startlat, startlon], {title: "Coordinates", alt: "Coordinates", draggable: true}).addTo(map).on('dragend', function() {
     var lat = myMarker.getLatLng().lat.toFixed(8);
     var lon = myMarker.getLatLng().lng.toFixed(8);
     var czoom = map.getZoom();
     if(czoom < 18) { nzoom = czoom + 2; }
     if(nzoom > 18) { nzoom = 18; }
     if(czoom != 18) { map.setView([lat,lon], nzoom); } else { map.setView([lat,lon]); }
     document.getElementById('lat').value = lat;
     document.getElementById('lon').value = lon;
     myMarker.bindPopup("Lat " + lat + "<br />Lon " + lon).openPopup();
    });
    
    function chooseAddr(lat1, lng1)
    {
     myMarker.closePopup();
     map.setView([lat1, lng1],18);
     myMarker.setLatLng([lat1, lng1]);
     lat = lat1.toFixed(8);
     lon = lng1.toFixed(8);
     document.getElementById('lat').value = lat;
     document.getElementById('lon').value = lon;
     myMarker.bindPopup("Lat " + lat + "<br />Lon " + lon).openPopup();
    }
    
    function myFunction(arr)
    {
     var out = "<br />";
     var i;
    
     if(arr.length > 0)
     {
      for(i = 0; i < arr.length; i++)
      {
       out += "<div class='address' title='Show Location and Coordinates' onclick='chooseAddr(" + arr[i].lat + ", " + arr[i].lon + ");return false;'>" + arr[i].display_name + "</div>";
      }
      document.getElementById('results').innerHTML = out;
     }
     else
     {
      document.getElementById('results').innerHTML = "Sorry, no results...";
     }
    
    }
    
    function addr_search()
    {
     var inp = document.getElementById("addr");
     var xmlhttp = new XMLHttpRequest();
     var url = "https://nominatim.openstreetmap.org/search?format=json&limit=3&q=" + inp.value;
     xmlhttp.onreadystatechange = function()
     {
       if (this.readyState == 4 && this.status == 200)
       {
        var myArr = JSON.parse(this.responseText);
        myFunction(myArr);
       }
     };
     xmlhttp.open("GET", url, true);
     xmlhttp.send();
    }
    
    </script>
    
    </body>
    </html>

    【讨论】:

      【解决方案3】:

      已经为 Leaflet 开发了一个很棒的地理编码器。

      https://github.com/smeijer/L.GeoSearch

      您可以像这样轻松使用结果

      map.on('geosearch_showlocation', function (result) {
          L.marker([result.x, result.y]).addTo(map)
      });
      

      【讨论】:

      • 我想传递地址 & 作为回报,我想得到纬度和经度。有没有做这个的api。
      • 正确。这就是这个插件的作用。您输入一个地址,它会找出该地址的地理坐标。您在事件触发数据中访问所述地理数据。(以上结果)
      • 如果您说要绕过用户输入并直接使用代码进行操作,那也很简单。只需使用control.geosearch('New York, NY')
      • 你能举个例子吗?
      • 我想通过 latLng 获取街道名称,我该怎么做?
      【解决方案4】:

      另一种解决方案,无需使用任何插件。我正在从 Mongo DB 读取数据,然后使用 Javascript、Angular(不是必需的)和 Leaflet 库来绘制我们从 Mongo DB 获得的坐标的标记。

      HTML

      只显示传单 div 和我们传递用户日期和电子邮件的 onclick 事件。此信息将传递给 MongoDB 以获取用户在给定时间范围内的纬度和经度集

      <div class="map" leaflet [leafletOptions]="historicalOptions">
              <div *ngFor="let l of historicalLayers" [leafletLayer]="l"></div>
            </div>
      
      <div class="col-lg-3 d-flex justify-content-center align-items-center">
                <button type="button" (click)="getHistoricalData(onDate,fromTime,toTime,user.email)" class="btn btn-primary p-4">
                  Get Map
                </button>
              </div>
      

      代码

      ngOnInit() {
      
      this.historicalOptions = {
        layers: [
          tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '...' }),
          this.heatmapLayer
        ],
        center: latLng(xxxxxxx, xxxxxxx),
        zoom: 16
      };
      }
      
      public getHistoricalData(onDate: Date, fromTime: Date, toTime: Date, userEmail) {
      
      this.historicalLayers = [];
      this.apiService.getGPSLocations(fromDate.toISOString(), toDate.toISOString(), userEmail)
          .subscribe(data => {
      
            if (data && data.length) {
      
              const markerLayers = this.drawMarkerPlotline(data, 'blue');
              this.historicalLayers = markerLayers;
      
            }
          }
      }
      
      private drawMarkerPlotline(data, color) {
      if (data) {
        let rawData;
        if (typeof data === 'string')
          rawData = JSON.parse(data);
        else
          rawData = data;
        const layers = [];
        if (rawData.length) {
          this.heatmapData.data = [];
          rawData.forEach((point, index) => {
            if (point && point.sensorValue && point.sensorValue.attr_lat && point.sensorValue.attr_lng) {
              const markerLayer = marker([point.sensorValue.attr_lat, point.sensorValue.attr_lng], {
                icon: icon({
                  iconSize: [15, 15],
                  iconAnchor: [7, 7],
                  iconUrl: this.getIconPath(color)
                }),
                title: new Date(point.observationTimestamp).toLocaleString(),
              });
              markerLayer.userId = point.userAccount.userId;
      
              layers.push(markerLayer);
      
              this.heatmapData.data.push({
                lat: point.sensorValue.attr_lat,
                lng: point.sensorValue.attr_lng,
                // count: 1
              });
            }
          });
          this.heatmapLayer.setData(this.heatmapData);
      
          return [layerGroup(layers)];
        }
      }
      return null;
      }
      
      private getIconPath(color) {
      let icon: string;
      switch (color) {
        case 'green':
          icon = 'assets/green-circle.png'
          break;
        case 'orange':
          icon = 'assets/orange-circle.png'
          break;
        default:
          icon = 'assets/blue-circle.png'
          break;
      }
      return icon;
      }
      

      注意

      代码 sn-ps 直接取自我的示例应用程序。因此,在需要的地方进行更改以满足您的要求。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多