将 String 转换为 javascript 中的 [x, y] 坐标

Convert Sting to [x, y] coordinates in javascript

<script type="text/javascript">
  var src = [40.6976, -74.2598];

  function convertToDMS(src) {
    function toDMS(n) {
      n = Math.abs(n);
      var d = Math.floor(n);
      n = n - d;
      n *= 60;
      var m = Math.floor(n);
      n = n - m;
      n *= 60;
      var s = Math.floor(n);
      return "" + d + " " + m + " " + s;
    }

    var dir0 = src[0] > 0 ? "N" : "S";
    var dir1 = src[1] > 0 ? "E" : "W";

    console.log(toDMS(src[0]) + dir0);
    console.log(toDMS(src[1]) + dir1);
  }

  convertToDMS(src);
</script>
<div id="locationdiv">[40.6976,-74.2598]</div>

使用上面的脚本我可以获得度、分和秒,例如 40°41'46.0"N+74°18'08.0"W

However if instead of using 
var src = [40.6976,-74.2598];
I use
var src = document.getElementById("locationdiv").innerHTML;

脚本无法正常工作,控制台中没有错误。如何将以字符串形式出现的 innerHTML 转换为可以使用的 [40.6976,-74.2598] 形式。

检查 typeof"string"
如果为 true — 使用 JSON.parse

将参数值转换为 Object

function toDMS(n) {
  n = Math.abs(n);
  const d = Math.floor(n);
  n = n - d;
  n *= 60;
  const m = Math.floor(n);
  n = n - m;
  n *= 60;
  const s = Math.floor(n);
  return `${d}° ${m}' ${s}"`;
}

function convertToDMS(latLng) {

  if (typeof latLng === "string") latLng = JSON.parse(latLng);
  const [lat, lng] = latLng;

  const dirLat = lat > 0 ? "N" : "S";
  const dirLng = lng > 0 ? "E" : "W";

  console.log(`${toDMS(lat)} ${dirLat}`);
  console.log(`${toDMS(lng)} ${dirLng}`);
}

convertToDMS([40.6976, -74.2598]);
convertToDMS(document.querySelector("#locationdiv").textContent);
<div id="locationdiv">[40.6976,-74.2598]</div>