我有一张 map 和一个包含餐厅信息的 JSON 文件。我需要从 JSON 文件向 map 添加 20 家餐厅的标记,但我无法加载带有标记的 map 。我认为我没有正确从 JSON 文件中检索数据。如果能指出正确的方向,我们将不胜感激。
这是我的代码:
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(55.9753905, -1.6236163),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new
google.maps.Map(document.getElementById("EstablishmentCollection"),
mapOptions);
$.getJSON("'FHRS_json.json'", function(json1) {
$.each(json1, function(key, data) {
var latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
title: data.BusinessName
});
marker.setMap(map);
});
});
这是 JSON 文件开头的示例。餐馆有很多,所以我不会全部发布。
{
"FHRSEstablishment": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"Header": {
"ExtractDate": "2018-02-03",
"ItemCount": "2369",
"ReturnCode": "Success"
},
"EstablishmentCollection": {
"EstablishmentDetail": [
{
"FHRSID": "1011573",
"LocalAuthorityBusinessID": "17/00395/MIXED",
"BusinessName": "#Central",
"BusinessType": "Pub/bar/nightclub",
"BusinessTypeID": "7843",
"AddressLine1": "15 Marlborough Crescent",
"AddressLine2": "Newcastle upon Tyne",
"PostCode": "NE1 4EE",
"RatingValue": "AwaitingInspection",
"RatingKey": "fhrs_awaitinginspection_en-GB",
"RatingDate": { "-xsi:nil": "true" },
"LocalAuthorityCode": "416",
"LocalAuthorityName": "Newcastle Upon Tyne",
"LocalAuthorityWebSite": "http://www.newcastle.gov.uk/",
"LocalAuthorityEmailAddress": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa8a8988ba949f8d999b898e969fd49d958cd48f91" rel="noreferrer noopener nofollow">[email protected]</a>",
"SchemeType": "FHRS",
"NewRatingPending": "False",
"Geocode": {
"Longitude": "-1.62244200000000",
"Latitude": "54.96785900000000"
}
},
最佳答案
我认为您遇到的主要问题是您需要解析 float 。目前它们只是字符串。您可以使用以下函数创建标记。只需将设施作为对象传递到函数中,它就会为您创建标记:
function createMarker(obj) {
const LatLng = new google.maps.LatLng(
parseFloat(obj.geocode.Latitude),
parseFloat(obj.gecode.Longitude)
); marker = new google.maps.Marker({
position: LatLng,
map: map,
title: obj.BusinessName
});
}
关于javascript - 使用 json 文件向 Google map 添加多个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50089336/