dongyu4554 2018-06-05 16:50
浏览 166
已采纳

JQuery:如何使用json中的Coordinates添加Leaflet标记

I have a problem creating a marker on my leaflet map with coordinates from a json array.

json example:

{"id":"1","longitude":"8.1876","latitude":"50.1297","name":"Rhineland-Palatinate"}

(background info: this comes from a PHP file that fetches data from a database which updates the current position every 10 seconds)

The jquery code: It creates the map on my html and upon the "get_marker" click event it starts ajax which pulls a new json every 10 seconds from my .php file

$(document).ready(function () { 
            var map = L.map('map', {
                center: [50.0231, 8.8849],
                zoom: 9
            });
            L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);

$("#get_marker").click(function(event){
   startajax();
  alert("get marker clicked");
 }); 

$("#delete_marker").click(function(event){
   deletemarkers();
      alert("marker deleted");
 });

function startajax () { 
  $.ajax({
  url: ('query_fetcharray.php'),
  data: {},
  type: 'POST',
  timeout: 10000,
  dataType: 'json',
  error: function() { 
    alert('Error, no Data received!');
  },
  success: drawmarker
  }) 
 };

everything above seems to be working fine The Problem is getting the actual marker on the map with the json coordinates. Nothing shows up on my map.

I tried accessing the long and lat values with json.longitude/json.latitude and then converting these into float => then saved in JS variables: var longitude. I then put the varibles into the L.marker.

my code:

function drawmarker (json) {    
        var longitude = parseFloat(json.longitude);
        var latitude = parseFloat(json.latitude);

        L.marker([longitude, latitude], {
               clickable: true
          })
               .bindPopup('hello')
                .addTo(map);    
};

The Problem seems to be the actual variables since hardcoding a set of coordinates into L.marker works fine.

  • 写回答

1条回答 默认 最新

  • douya7309 2018-06-06 07:08
    关注

    I think you're over-thinking the floating point issue. Try this simpler way:

    function drawmarker (json) {    
            var longitude = json.longitude;
            var latitude =  json.latitude;
    
            L.marker([latitude, longitude])
                   .bindPopup('hello')
                    .addTo(map);    
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。