javascriptbrowservue.jsw3c-geolocation

How can I access the Coordinates constructor directly in JavaScript?


Type checking in Vue requires the constructor function to be passed in as the type:

props: {
  coords: {
    type: Coordinates,
    required: true,
  },
},

I can't work out how to find the Coordinates constructor. Can't use Object because it doesn't inherit from anything, and would prefer not to just allow anything.

There's nothing on MDN about how to access it directly: https://developer.mozilla.org/en-US/docs/Web/API/Coordinates

Any ideas?

EDIT: To clarify, window.Coordinates is undefined. The above code example doesn't work.


Solution

  • Coordinates is not something exposed in the browser to be used by web developers. It's an interface defined by W3C geo specs, for browser vendors who implement the geolocation features. An interface describes how a certain type of data structure looks like. For example, coords in the following example:

    navigator.geolocation.getCurrentPosition(function (pos) {
      var coords = pos.coords
      console.log(coords)
    })
    

    Even though you could retrieve the literal of Coordinates with following code. It's just an object (yes, it's prototype, not constructor), you can barely do anything.

    Object.getPrototypeOf(pos.coords)
    

    So two points here:

    1. Coordinates is not for web developers.
    2. Coordinates is not even a function.

    The only way I guess, is to define your own validator and check whether the input value meets your requirement. This would be easier because Coordinates has a special toString() symbol:

    props: {
      coords: {
        validator: function (value) {
          return value.toString() === '[object Coordinates]'
        }
      }
    }
    

    However, this validator may fail if you hand-craft your own coords data. A more generic way is like duck-typing, just check whether it has proper properties you need, latitude and longitude usually.