The openlayers 3 function ol.proj.transform seems to be mysteriously turning live geolocation data into a string

I came across an interesting solution on stackoverflow for dynamically inserting data into a map using OpenLayers 3.*. Everything seems to be working fine when I directly input the numbers like this:

 geometry: new ol.geom.Point(ol.proj.transform([-72.0704,46.678],'EPSG:4326','EPSG:3857')),

However, things take a strange turn when I attempt to use JSON data as shown in the following code:

  • Replacing only the longitude displays the marker correctly,
  • Substituting only the latitude results in zero latitude value,
  • When substituting both longitude and latitude, the marker disappears.

    function AddMarkers() {
    var iconFeatures=[];
    data  = [{"longitude":"-72.0704","latitude":"46.678"},{"longitude":"-73.1234","latitude":"45.678"},{"longitude":"46.738586","latitude":"24.774265"}];
    
    var iconFeature = new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.transform([data[0].longitude,46.678], 'EPSG:4326',     
      'EPSG:3857')),
      name: 'Null Island',
      population: 4000,
      rainfall: 500
    });
    
    var iconFeature1 = new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.transform([28.7753927 , data[1].latitude], 'EPSG:4326',     
      'EPSG:3857')),
      name: 'Null Island Two',
      population: 4001,
      rainfall: 501
    });
    var iconFeature2 = new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.transform([data[2].longitude,data[2].latitude], 'EPSG:4326',     
      'EPSG:3857')),
      name: 'Null Island Two',
      population: 4002,
      rainfall: 502
    });
    iconFeatures.push(iconFeature);
    iconFeatures.push(iconFeature1);
    iconFeatures.push(iconFeature2);
    
    var vectorSource = new ol.source.Vector({
      features: iconFeatures //add an array of features
    });
    
    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: 'images/icon.png'
      }))
    });
    
    
    var vectorLayer = new ol.layer.Vector({
      source: vectorSource,
      style: iconStyle
    });
    
    return vectorLayer;
    

    }

Why does this puzzling behavior occur only when using data from a JSON array, but not when manually inputting the values?

Answer №1

When utilizing php json encoding, I am using json_encode() and including quotation marks around the data. To remove these quotation marks from the longitude and latitude values, I need to trim them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is my jQuery code generating a large number of DOM objects?

I am currently developing a hex dumper in JavaScript to analyze the byte data of files provided by users. To properly display a preview of the file's data, I am utilizing methods to escape HTML characters as outlined in the highest-rated answer on thi ...

Exploring JSON nested objects with jQuery UI Autocomplete

I'm attempting to implement the jQuery UI Autocomplete widget with a customized JSON feed received from an API. The format of the JSON data is as follows: { "SearchTerm": "ches", "HasDirectCountyHit": false, "DirectCountyHitId": null ...

The server-side PHP script may not always successfully respond to an Ajax call from the client

Whenever I try to access my index.html site, there are times when the Ajax request is made to call the PHP on the server in order to display the dynamic content. But for some reason, it only works intermittently when I manually refresh the page using the a ...

Optimal methodologies for AngularJS components in content management system-based applications

Seeking the optimal approach for creating Angular 1 components with a CMS-driven strategy. My goal is to develop various label templates in a component-driven, highly reusable manner, fueled by CMS content. My plan is to utilize JSON as a component tree ...

Remove duplicate records by grouping by similar items

I have a data string stored in a MySQL database that looks like this: {"StateId":73,"CallTime":"\/Date(1336365498912+0500)\/","CallId":"1336365489.14157","Target":"agi://127.0.0.1"}},"Profile":{"$type":"DataWriter.DbProfile, DataWriterObjects"," ...

Eliminate error class in jQuery Validate once validation is successful

I'm having an issue with the jQuery Validate plugin. Even after a field is successfully validated, the "error-message box" continues to be displayed. How can I remove this box? Here's my code: CSS: .register-box .field .has-error{ border ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

Transferring the size of a JSON array via socket connection (Java to Python)

Currently, I am in the process of establishing a connection between a Java client and a Python server operated by my colleague. Our immediate goal at the moment is to transmit a JSON array. In our approach, we initiate communication by sending the length o ...

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

Angular version 6: The 'fromEvent' property is not found on the 'Observable' type

I am working on developing a custom sticky navbar directive for the sticky header in my angular 6 application. This is what I have accomplished so far: import { Directive, Input, Renderer, ElementRef, OnInit } from '@angular/core'; import { Obs ...

Having trouble with radio button validation in JS?

I'm having difficulty understanding why the radio button is not staying checked when I select another option. To demonstrate, I created a fiddle where initially the "diy" button is selected but switching to "paid" causes the radio button to jump back ...

tips for deactivating routerLink functionality on anchor elements

Working on an Angular application that requires me to create an image slider. However, due to the presence of router links in the application, the anchor tags in the image slider keep redirecting. I want to prevent this redirection and instead successful ...

Issue with making Flickr API request using XMLHttpRequest receiving an unsuccessful response

I'm having issues trying to retrieve a JSON list from Flickr using plain JavaScript and XMLHttpRequest. Here is an example of an AJAX call without a callback function that is not functioning properly: var url = "https://api.flickr.com/services/feed ...

a reliable approach to gain entry to properties that do not exist

Utilizing Google Apps Script along with JavaScript code, I am leveraging UrlFetchApp to retrieve data from the Stripe API in order to fetch an invoice. Subsequently, the Script processes the retrieved data and updates a Google Sheet template with it. An i ...

Tips for loading a webpage when a button is clicked with the help of jQuery AJAX and PHP:

Is it possible to dynamically load a page on button click, pass data to the new page using jQuery AJAX, and place the received value in an input field within the loaded page? Basically, the scenario is as follows: A button named "Something" triggers the l ...

Modify a specific Object within an array located within another Object

Hello there, I need some help with updating the value of an Object that is nested within an array in another Object! { "_id" : ObjectId("5a641fc1b66d0a1b7c274c99"), "comments" : [ { "author" : { "id" : ObjectId("5a5c93954c5b6f35953d38e0"), ...

How to Implement Filtering in AngularJS ng-repeat

While developing my app, I came across a challenge with the filter in my ng-repeat. Initially, I could search by productCode or name. Then, a new requirement emerged - "Filter by SubcategoryId." The issue lies in filtering strictly by subCategoryId, while ...

Tips for retrieving reverse geocodes using PHP cURL and JSON:

How can I echo only the formatted address from a JSON response using PHP? Here is the code I currently have: <?PHP $ch = curl_init(); $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=22.569794,88.357934'; curl_setopt($ch, CUR ...

What is the best way to generate a list from a text file in javascript?

I have a document called department.txt which lists various departments: Chemistry Physics Mathematics Other I'm looking to generate a dropdown menu <select> in my HTML by importing this file. How can I achieve this using Javascript? There are ...

The background image's fadeInOut transitions create a strange phenomenon where all the text appears in white

So, here's a strange issue I'm facing. On my website, the background image changes with a smooth fadeIn/Out transition. Video: Website in action: Here is the HTML markup: <div class="fondo" onclick="descargar(2,500);descargar(1,500);"> ...