Я создаю проект udacity для карт окрестностей, в котором я должен пометить местоположение, и при щелчке по маркеру он должен отображать информацию из другого API. Я могу получить данные из API, но не могу добавить в свой инфоблок. Ниже я предоставляю полный код:
когда я пытаюсь вызвать из строки 94, я не получаю никакого массива. Мне нужны данные в строке 96, чтобы добавить информационное окно. Я не могу получить данные из функции popContent.
var map;
var platform = new H.service.Platform({
'app_id': 'app_id',
'app_code': 'app_code'
});
// Obtain the default map types from the platform object:
var defaultLayers = platform.createDefaultLayers();
// Instantiate (and display) a map object:
var map = new H.Map(
document.getElementById('map'),
defaultLayers.normal.map,
{
zoom: 10,
center: { lat: 19.0760, lng: 72.8777 }
});
// Create the default UI:
var ui = H.ui.UI.createDefault(map, defaultLayers);
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
//data for marker
var Location = function(title,lat, lng){
var self = this;
this.title = title;
this.lat = lat;
this.lon = lng;
//get content of marker location
this.popContent = function(newtitle,newlat,newlon){
var markerarray = [];
var foursquareURL = 'https://api.foursquare.com/v2/venues/search?ll='+newlat+','+newlon+'&client_id=&client_secret=&v=20180908&query='+newtitle+'';
//Using Foursquare API to get info about the restaurant
$.getJSON(foursquareURL).done(function(data) {
var results = data.response.venues[0];
self.name = results.name;
self.street = results.location.formattedAddress[0];
self.city = results.location.formattedAddress[1];
self.postalCode = results.location.postalCode;
markerarray.push(self.name,self.street,self.city,self.postalCode);
}).fail(function() {
alert("There was an error with the Foursquare API call. Please refresh the page and try again to load Foursquare data.");
});
return markerarray;
};
//info window
this.addMarkerToGroup = function (group, coordinate, html) {
var marker = new H.map.Marker(coordinate);
// add custom data to the marker
marker.setData(html);
group.addObject(marker);
};
//open infowindow for location marker
this.openinfowindow = function(map) {
var group = new H.map.Group();
map.addObject(group);
// add 'tap' event listener, that opens info bubble, to the group
group.addEventListener('tap', function (evt) {
// event target is the marker itself, group is a parent event target
// for all objects that it contains
var bubble = new H.ui.InfoBubble(evt.target.getPosition(), {
// read custom data
content: evt.target.getData()
});
// show info bubble
ui.addBubble(bubble);
}, false);
var datahtml = this.popContent(this.title,this.lat,this.lon);
this.addMarkerToGroup(group, {lat:this.lat, lng:this.lon},'<div><a href = "#" >'+datahtml[0]+'</a>' + '</div><div >'+datahtml[1]+'<br>' + datahtml[2]+'<br>'+datahtml[3]+'</div>');
};
this.openinfowindow(map);
//assign click event for marker
};
var locationsModel = {
//array
locations:[
new Location('Kanjurmarg',19.1317,72.9352),
new Location('Thane', 19.2183, 72.9781),
new Location('Powai', 19.1197, 72.9051),
],
query: ko.observable(''),
};
// Search function for filtering through the list of locations based on the name of the location.
locationsModel.search = ko.dependentObservable(function() {
var self = this;
var search = this.query().toLowerCase();
return ko.utils.arrayFilter(self.locations, function(location) {
return location.title.toLowerCase().indexOf(search) >= 0;
});
}, locationsModel);
//search function for filtering locations
ko.applyBindings(locationsModel);
#map{
height: 400px;
width:100%;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Neighborhood project</title>
<!-- optimum performance on mobile device -->
<meta name = "viewport" content = "initial-scale=1.0, width=device-width" />
<!-- loads the module -->
<script src = "http://js.api.here.com/v3/3.0/mapsjs-core.js"
type = "text/javascript" charset = "utf-8"></script>
<script src = "http://js.api.here.com/v3/3.0/mapsjs-service.js"
type = "text/javascript" charset = "utf-8"></script>
<script src = "http://js.api.here.com/v3/3.0/mapsjs-ui.js"
type = "text/javascript" charset = "utf-8"></script>
<link rel = "stylesheet" type = "text/css"
href = "http://js.api.here.com/v3/3.0/mapsjs-ui.css" />
<script type = "text/javascript" src = "https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
<!-- custom stylesheet -->
<link rel = "stylesheet" type = "text/css" href = "css/style.css">
</head>
<body>
<h2>Neighborhood Maps</h2>
<div id = "map"></div>
<div class = "search-area" id = "search-area">
<input class = "search-input" placeholder = "Search for Places..." type = "text" name = "q" data-bind = "value: query, valueUpdate: 'keyup'">
<ul class = "location-list" data-bind = "visible:query, template: {name: 'location', foreach: search}">
</ul>
</div>
<script
src = "https://code.jquery.com/jquery-3.3.1.js"
integrity = "sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60 = "
crossorigin = "anonymous"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"></script>
<script src = "js/knockout-3.4.2.js" charset = "utf-8"></script>
<script src = "js/test.js"></script>
</body>
</html>
Это потому, что $.getJSON
внутри popContent
является асинхронным и не возвращает значения немедленно. В вашем коде this.popContent()
всегда будет возвращать пустой массив.
Что вам нужно сделать, так это сделать ваш код зависимым от этого ответа $.getJSON
. Первый способ - обернуть все обратным вызовом $.getJSON
. Второй способ - использовать обещания.
Ваш снайпер не работает. Удалите все вещи, такие как тег
head
, и вместо этого поместите эти ссылки в качестве ресурсов, щелкнув «Добавить внешнюю библиотеку» и добавив все, что вам нужно, одну за другой. Также удалите ссылку наtest.js
.