javascript - OpenLayers 和 JSON 中的坐标

标签 javascript json coordinates openlayers

首先,我是西类牙人,所以很抱歉我的英语。

我对坐标和 OpenLayers 有疑问。

问题是,当我直接在代码中写入坐标时,名为“mapa_tren”的函数正在工作,如果我这样写:

geometry: new ol.geom.Point(transformacion(-4.231575155, 43.308034436))

map 显示正确,但如果我这样写:

geometry: new ol.geom.Point(transformacion(resp.long, resp.lat )),

map 显示在海洋中。

我检查了json,我检查了使用json的函数,没有发现任何错误

这是代码:

    function transformacion(lng, lat) {//Funcion para convertir las coordenadas
       return ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857');
    }   

function mapa_tren(resp) {//Function que contiene el código paramostrar el mapa

var capa1 = new ol.layer.Tile({
          source: new ol.source.MapQuest({layer: 'sat'})
      });

 var capa2 = new ol.layer.Tile({
          source: new ol.source.MapQuest({layer: 'hyb'})
      });


var iconFeature = new ol.Feature({ 
   geometry: new ol.geom.Point(transformacion(resp.long, resp.lat )),
   //geometry: new ol.geom.Point(transformacion(-4.231575155, 43.308034436)),
   name: 'Tren'
});


var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    opacity: 0.75,
    src: 'icono_localizacion.png'
    }))
});

iconFeature.setStyle(iconStyle);

var vectorSource = new ol.source.Vector({
    features: [iconFeature]
});

var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
});


 var map = new ol.Map({
    target: document.getElementById('map'),
    layers: [capa1, capa2, vectorLayer],
    view: new ol.View({
      //center: ol.proj.transform([longitud, latitud ], 'EPSG:4326', 'EPSG:3857'),
      center: ol.proj.transform([-4.231575155, 43.308034436 ], 'EPSG:4326', 'EPSG:3857'),
      //center: [0,0],
      zoom: 7
    })
  });

}

function call_map(resp){
    mapa_tren(resp)
}


$.post('serv.php',{vble: 'real_sorpheo'}, function (json){ call_map(json) },"json")

最佳答案

正如评论中所表达的,我遇到了同样的问题:使用数字坐标可以工作,而放置 json 内容变量会导致失败。

解决方案很简单,我们只需要在 json 返回上完成 parseFloat 即可:

// add to map   
var mapItem = new ol.Feature({
        geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(unit.longitude), parseFloat(unit.latitude)])),
        name: unit.devid,
        online: unit.online,
        outdoor: unit.outdoor,
        chart24h: "http://www.uradmonitor.com/data/0.1/charts/'+unit.devid+'.usvh.png"  
});
vectorSource.addFeature(mapItem);

这对我来说很有效: enter image description here

关于javascript - OpenLayers 和 JSON 中的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538669/

相关文章:

php - 使用 PHP 动态创建内容的 JSON mime 类型

javascript - 如何让一个对象绕着html5 Canvas 中的一个点转动

php - 寻找简单 HTML 游戏的设计/架构建议

javascript - 将参数传递给函数。怎么了?

java - 如何为 Gson 编写自定义 JSON 反序列化器?

javascript - 使用鼠标移动沿斜线移动坐标

java - LinkedHashSet 不删除重复项

javascript - 开发新的 Angular 应用程序 - 为 Angular 2 做准备

javascript - 客户端函数未被调用 SignalR

javascript - 没有动态数据的外部 json 文件有什么优点?