Значение из Google GeoCode API не будет возвращено должным образом - PullRequest
0 голосов
/ 04 ноября 2018

Я боролся с этой единственной ошибкой для проекта, которым я занимаюсь в классе веб-дизайна уже около дня, и я не близок к тому, чтобы выяснить, как ее решить. Для проекта я использую комбинацию двух API для чтения в указанном пользователем местоположении, получения широты и долготы этого местоположения с помощью Google GeoCoding API, а затем с помощью этой широты и долготы отображаем текущую погоду в этом месте. Проблема заключается в том, что независимо от того, что я делаю, функция, которую я сделал, чтобы вернуть объект Location (имя, широту и долготу) в основной файл-скрипт index.html, никогда не возвращается должным образом, и я полагаю, что это может быть потому, что он работает асинхронно , Я немного новичок в javascript, поэтому заранее приношу свои извинения, если я задам много вопросов на ваши ответы. Вот код из моего файла location.js:

class Location
{
    constructor(name = "Dummy Location", lat = 0.0, lng = 0.0)
    {
        this.name = name;
        this.lat = lat;
        this.lng = lng;
    }
}
function geocode(location)
{
    axios.get('https://maps.googleapis.com/maps/api/geocode/json?',
    {
        params: { 
            address: location, 
            key: googleAPIKey
        }
    })
    // Get a reponse from that request
    .then(function(response)
    {
        ///Format the address
        var formattedAddress = response.data.results[0].formatted_address;
        // Get the various address components
        var locationName = `${response.data.results[0].address_components[0].long_name}, ${response.data.results[0].address_components[2].short_name}`;
        var locationLat = response.data.results[0].geometry.location.lat;
        var locationLng = response.data.results[0].geometry.location.lng;
        // Create a new Location based on those components
        var geoLocation = new Location(locationName, locationLat, locationLng);
        // (Debug) Log that location
        console.log(geoLocation);
        // Return that location
        return geoLocation;
    })
    .catch(function(error)
    {
        console.log(error);
    })
}

А вот код из моего index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Cool Weather App</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <link rel = "stylesheet" href="css/styles.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

</head>
<body>
    <header>
    <div id = "locationinputcontainer">
        <input id="locationfield" type="text" value="Location">
        <input id = "submitbutton" type="submit" value="Submit">
        <input id = "savelocationbutton" type = "submit" value = "Save Location">
    </div>
    </header>
    <div id = "locationweathercontainer">
        <h1 id = "locationname">Dummy Value</h1>
        <h2 id = "weather">Weather</h2>
        <h1 id = "temperature">68&deg;F</h1>
        <h3 id = "precipitation">Precipitation:</h3>
        <h3 id = "humidity">Humidity: </h3>
        <h3 id = "windspeed">Wind Speed: </h3>
    </div>
    <div id = "mylocationscontainer" class = "dropdowncontainer" style = "float:left">
        <h1>My Locations</h1>
        <ol>
        </ol>
    </div>
    <div id = "settingscontainer" class = "dropdowncontainer" style = "float:right">
        <h1>Settings</h1>
    </div>
</body>
<script src = "js/location.js"></script>
<script>
    const locationField = document.querySelector("#locationfield");
    const submitButton = document.querySelector("#submitbutton");
    const saveButton = document.querySelector("#savelocationbutton");
    const locationNameElement = document.querySelector("#locationname");
    const locationsListElement = document.querySelector("#mylocationscontainer");

    const prefix = "asb9599-";
    const storedLocationsKey = prefix + "storedLocations";
    const storedCurrentLocationKey = prefix + "storedCurrentLocation";
    let currentLocation;
    let locationInput;

    /* Functions */
    function UpdateCurrentLocation()
    {
        currentLocation = geocode(locationInput);
        console.log("(index.html) Current Location: " + currentLocation);
        locationNameElement.innerHTML = currentLocation.name;
    }
    /* Events */
    submitButton.onclick = UpdateCurrentLocation;
    locationField.onchange = e => {locationInput = e.target.value};
</script>
</html>

И вот ответ, который я получаю: Образец ответного изображения

1 Ответ

0 голосов
/ 04 ноября 2018
params: { 
            address: location, 
            key: googleAPIKey(paste your apikey here)
        }

Получите ключ API от Google и вставьте его вместо ключа. В противном случае он не будет работать.

...