2017-03-09 4 views
1

Ich mache eine Karte mit Markern. Ich habe die Geokoordinaten vom Abrufen einer Google API Url. Aber für die Marker brauche ich zusätzliche Informationen von anderswo. Ist es möglich, diese zusätzlichen Informationen an die Antwort, die ich vom Abrufen der URL erhalten habe, anzuhängen? Danke vielmals!
Der Code:Ein neues Feld zu Javascript hinzufügen Fetch Antwortobjekt

var location = "Seattle"; 
var username = "Test user"; 
var time = "8th March 2017"; 

function toMap(location, username, time) { 
    if (location.length > 0) { 
     var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key=Your_API_Key"; 
     fetch(googleURL) 
      .then(function(response) { 

    // Can I add "location", "username", and "time" to the response result here 
    // before returning it????? 

       return response.json(); 
      }) 
      .then(addMarker); 
    } 
} 

Antwort

1

Da response.json() gibt ein Promise von Object, können Sie es tun in ein weiterer then() Rückruf.

var location = "Seattle"; 
var username = "Test user"; 
var time = "8th March 2017"; 

function toMap(location, username, time) { 
    if (location.length > 0) { 
     var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key=Your_API_Key"; 
     fetch(googleURL) 
      .then(function(response) { 
       return response.json(); 
      }) 
      .then(function(json) { 
       json.location = location; 
       json.username = username; 
       json.time = time; 
       return json; 
      }) 
      .then(addMarker); 
    } 
} 
0

Natürlich können Sie ein beliebiges Feld hinzufügen, können Sie die Antwortobjekt wollen

des

fetch(googleURL) 
      .then(function(response) { 
       //set these values to anything 
       response.location = ""; 
       response.username = ""; 
       response.time = ""; 

       return response.json(); 
      }) 
      .then(addMarker); 
+0

Hinweis, "Antwort" ist nicht "response.json()" – guest271314

1

Body.json() Die json() Methode des Body mixin sagen Lassen Sie nimmt a Response streamen und liest es zu completio n. Sie gibt ein Versprechen zurück, das mit einem Objektliteral aufgelöst wird, das die JSON-Daten enthält.

Sie können Kette .then() zu .json(), innerhalb .then() Handler Rufgabe- Eigenschaften, Werte bei javascript Ebene Objekt, return Objekt als Parameter

fetch(googleURL) 
    .then(function(response) { 

    // Can I add "location", "username", and "time" to the response result here 
    // before returning it????? 

    return response.json().then(function(json) { 
     json.location = "abc"; 
     json.username = "def"; 
     json.time = 123; 
     return json; 
    }); 
    }) 
    .then(addMarker); 
Verwandte Themen