В Vue. js как я могу получить json данные из API ThingSpeak и использовать координаты на карте Google? - PullRequest
0 голосов
/ 04 февраля 2020

Я создаю Vue JS приложение. Я установил пакет vue - google-maps.

Кроме того, у меня есть GPS-трекер, настроенный для отправки данных в ThingSpeak API.

Что я хочу сделать, это получить последнюю координату в API и отобразить ее на карте Google.

Мои компоненты \ GoogleMap. vue использует этот код:

<template>
  <div>
    <GmapMap
      :options="{
          center: center,
          zoomControl: true,
          streetViewControl: false,
          clickableIcons: false,
          zoom: zoom,
          gestureHandling: 'auto',
          mapTypeId: 'hybrid'
      }"
      style="width:100%;  height: 500px;"
    >
      <GmapMarker
        :key="index"
        v-for="(m, index) in markers"
        :position="m.position"
        :clickable="true"
        :draggable="false"
        @click="center=m.position"
      ></GmapMarker>
    </GmapMap>
  </div>
</template>

<script>
export default {
  name: 'GoogleMap',
  data () {
    return {
      // just a dummy location for now: Accra, in Ghana
      // change this to get the API location from ThingSpeak
      // this center is exported to the template
      center: { lat: 5.5912045, lng: -0.2497708 },
      zoom: 13,
      markers: [{
        position: { lat: 5.5912045, lng: -0.2497708 }
      }]
    }
  }
}
</script>

Кроме того, это мой src \ main. js:

(я забрал свой ключ API в целях безопасности)

import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import * as VueGoogleMaps from 'vue2-google-maps'

Vue.config.productionTip = false

Vue.use(VueGoogleMaps, {
  load: {
    key: <API_KEY_GOES_HERE>
  },
  installComponents: true
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

Когда я запускаю это, карта корректно отображается на моей веб-странице. Тем не менее, я не знаю, чтобы получить координаты из API ThingSpeak, а не напрямую жестко его кодировать!

Я новичок в Vue ...

Я смог сделать это в обычном JS, но я не могу сделать это в Vue ...

Вот что я сделал:

<!DOCTYPE html>
<html>
  <head>
    <title>Experiment</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>



    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>




    <script>
      // Initialize global variables



      // Initialize and add the map
      function initMap() {
        // get the last location sent 

        // get LATITUDE
        $.getJSON("https://api.thingspeak.com/channels/<CHANNEL_ID>/fields/1/last.json?api_key=<THINGSPEAK_READ_API_KEY>", function(result){

          var m = result;
          // set latitude as x
          x=Number(m.field1);

        });

        // get LONGITUDE
        $.getJSON("https://api.thingspeak.com/channels/<CHANNEL_ID>/fields/2/last.json?api_key=<THINGSPEAK_READ_API_KEY>", function(result){

          var m = result;
          // set longitude as y
          y=Number(m.field2);

        }).done(function (){

          coordinates = {lat: x, lng: y};


          // The map, centered at the location given
          var map = new google.maps.Map(
              document.getElementById('map'), {zoom: 13, center: coordinates});
          // The marker, positioned at the location given
          var marker = new google.maps.Marker({
            position: coordinates, 
            map: map,
            title: 'Click to get coordinates'
          });

          var infowindow = new google.maps.InfoWindow({
              content: '<p>Tracker Location: ' + marker.getPosition() + '</p>'
          });

          map.addListener('center_changed', function() {
            // 3 seconds after the center of the map has changed, pan back to the
            // marker.
            window.setTimeout(function() {
              map.panTo(marker.getPosition());
            }, 5000);
          });

          marker.addListener('click', function() {
            infowindow.open(map, marker);
            // when the marker is clicked, center map
            map.setCenter(marker.getPosition());
          });
        });





      }

    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=<API_KEY_GOES_HERE>&callback=initMap"></script>

  </body>
</html>

Так что в основном я Я просто пытаюсь повторить это, но в Vue. Спасибо ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...