首页 > 解决方案 > 如何在机械师/驾驶者应用程序中使路线响应返回当前位置的 json

问题描述

我正在使用 react native 和 sockect.io 创建一个机械师/驾驶者应用程序。我希望我的 routeResponse 返回当前位置的 json。我该怎么做?

这是我在 index.js 中使用 express 和 socket.io 的后端代码

const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
const port = 3000;
io.on("connection", socket => {  
    console.log("a user connected :D");
socket.on("repairRequest", routeResponse => {    
    console.log(routeResponse);  
    });
});
server.listen(port, () => console.log("server running on port:" + port));

这是 Motorist.js 的摘录。我想获取当前位置的 json

import React, { Component } from "react";
import {
  TextInput,
  StyleSheet,
  Text,
  View,
  Keyboard,
  TouchableHighlight,
  TouchableOpacity
} from "react-native";
import MapView, { Polyline, Marker } from "react-native-maps";
import apiKey from "../google_api_key";
import _ from "lodash";
import PolyLine from "@mapbox/polyline";
import socketIO from 'socket.io-client';

export default class Motorist extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: "",
      latitude: 0,
      longitude: 0,
      destination: "",
      predictions: [],
      pointCoords: []
    };
    // this.onChangeDestinationDebounced = _.debounce(
    //   this.onChangeDestination,
    //   1000
    // );
  }

  componentDidMount() {
    //Get current location and set initial region to this
    navigator.geolocation.getCurrentPosition(
      position => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude
        });
      },
      error => console.error(error),
      { enableHighAccuracy: true, maximumAge: 2000, timeout: 20000 }
    );
  }

  async getRouteDirections(destinationPlaceId, destinationName) {
    try {
      const response = await fetch(
        `https://maps.googleapis.com/maps/api/directions/json?origin=${
          this.state.latitude
        },${
          this.state.longitude
        }&destination=place_id:${destinationPlaceId}&key=${apiKey}`
      );
      const json = await response.json();
      console.log(json);
      const points = PolyLine.decode(json.routes[0].overview_polyline.points);
      const pointCoords = points.map(point => {
        return { latitude: point[0], longitude: point[1] };
      });
      this.setState({
        pointCoords,
        predictions: [],
        destination: destinationName,
        routeResponse: json
      });

标签: react-native-android

解决方案


推荐阅读