pageNotfoUnd
pageNotfoUnd

Reputation: 666

Fetch API with Google Directions API is not working in reactjs

async getDirections( ) {
    let resp = await fetch(`https://maps.googleapis.com/maps/api/directions/json?origin=13.010587,%2080.259151&destination=13.023261,%2080.277290`)
    let respJson = await resp.json();
    let points = Polyline.decode(respJson.routes[0].overview_polyline.points);
    let coords = points.map((point, index) => {
        return {
            latitude: point[0],
            longitude: point[1]
        }
    })
    this.setState({ coords: coords })
    return coords
}

This is my code. I am getting error as unable to fetch from google api

Upvotes: 1

Views: 1667

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58603

There is no issue with your code :

Issue is with Google direction api, if you want to call it from client side you must use their library,

Google disabled JSON-P callback for Geocoding to prevent abuse. You must use Google Geocoding API library to do the proper request, and the purpose of reverse Geocoding must be to show an address on Google Maps.


Hacked - Solutions : (Use proxy server)

async getDirections( ) {
    var proxy_url = 'https://cors-anywhere.herokuapp.com/';
    var target_url = 'https://maps.googleapis.com/maps/api/directions/json?origin=13.010587,%2080.259151&destination=13.023261,%2080.277290';
    var google_api_key = '&key=your_google_api_key'

    let resp = await fetch(`${proxy_url}${target_url}${google_api_key}`)
    let respJson = await resp.json();
    let points = Polyline.decode(respJson.routes[0].overview_polyline.points);
    let coords = points.map((point, index) => {
        return {
            latitude: point[0],
            longitude: point[1]
        }
    })
    this.setState({ coords: coords })
    return coords
}

Upvotes: 2

Related Questions