如何编写一个函数来使用地理编码绘制俄亥俄州的所有学校?

问题描述 投票:0回答:1

我已经在这个项目上工作了好几个月了,特别是在这个问题上至少四天了,所以我想我应该询问专家。我是 Web 开发新手,完全是自学成才,我正在寻求关于我的代码出错的地方的指导。

我正在尝试运行我的 CSV 文件,其中包含学校名称 (Name)、街道地址 (Address)、城市 (City)、邮政编码 (ZIP) 和州 (State)。

使用 Papa.parse 读取 CSV,我尝试通过 opencagedata 地理编码 API 传递此 CSV 信息。

我认为函数结构或变量名称一定有问题。 Web 开发人员工具显示 js 和 css 文件已正确加载。

map.js

// BENNETT DON'T TOUCH THIS !!!
var map = L.map('map').setView([39.983334, -82.983330], 9);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var baseMaps = {
    "Street View": L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'),
    "Satellite View": L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}')
};
L.control.layers(baseMaps).addTo(map);

// Test marker
L.marker([39.983334, -82.983330]).addTo(map)
    .bindPopup('Bennett Made A Popup!')
    .openPopup();

// Convert Papa.parse to return a Promise
function parseCSV(csvFile) {
    return new Promise((resolve, reject) => {
        Papa.parse(csvFile, {
            header: true,
            complete: results => resolve(results.data),
            error: error => reject(error)
        });
    });
}

async function geocodeAddress(address) {
    try {
        const encodedAddress = encodeURIComponent(address);
        const geocodingUrl = `https://api.opencagedata.com/geocode/v1/json?q=${encodedAddress}&countrycode=us&bounds=-84.99023,38.44498,-80.28809,42.56926&key=MY_API_KEY`;

        const response = await fetch(geocodingUrl);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }    
const response = await fetch(geocodingUrl);
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    
    if (data.results?.[0]?.geometry) {
        return data.results[0].geometry;
    }
    console.warn('No results found for address:', address);
    return null;
} catch (error) {
    console.error('Error geocoding address:', error);
    return null;
}
async function plotSchools(csvFile) { 
    try {
    // Fetch and parse CSV
        const response = await fetch(csvText);
        const csvText = await response.text();
        const schools = await parseCSV(csvText);

    // Process each school
    for (const school of schools) {
        const { "Street Address": Address, City, State, ZIP, Name } = school;
        
        if (!Address || !City || !State || !ZIP) {
            console.warn(`Incomplete address for school: ${Name}`);
            continue;
        }

        const fullAddress = `${Address}, ${City}, ${State} ${ZIP}`;
        
        const coords = await geocodeAddress(fullAddress);
        if (coords) {
                console.log(`Coordinates for ${Name}:`, coords.lat, coords.lng);
            L.marker([coords.lat, coords.lng])
                .addTo(map)
                .bindPopup(`<b>${Name}</b>`);
        } else {
            console.warn(`No coordinates found for ${Name}`);
        }
    }
} catch (error) {
    console.error('Error plotting schools:', error);
    throw error;
}
}// Initialize with proper CSV file path
plotSchools('data/school-data/ohioschools.csv')
    .catch(error => console.error('Failed to plot schools:', error));

index.html

My Community Map


<!--Linking CSS-->
<link rel="stylesheet" href="./css/styles.css"/>

<!--Linking Leaflet CSS-->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
 integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
 crossorigin=""/>

 <!--Linking Google Fonts-->
 <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap">
</head>
<body>
<div id="map" style="height: 500px;"></div>
</body>
javascript html mapping gis papaparse
1个回答
0
投票
const response = await fetch(csvFile);

发布的代码未正确获取csv文件(已通过尚未定义的

csvText
)。

© www.soinside.com 2019 - 2024. All rights reserved.