October 23, 2024
Chicago 12, Melborne City, USA
HTML

How to write a function to plot all of the schools in Ohio using geocoding?


I’ve been working on this project for many months now, and on this problem in particular for at least four days so I figured I’d ask the experts. I’m new to web development and entirely self-taught, and I’m seeking guidance on where my code is going wrong.

I’m trying to run through my CSV file which contains school names (Name), street addresses (Address), city (City), and zip code (ZIP), and state (State).

Using Papa.parse to read through the CSV, I’m trying to pass this CSV information through the opencagedata geocoding API.

I believe there must be an issue with either the function structure or the variable names. The web developer tool says that the js and css files are loading properly.

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/leaflet@1.9.4/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>



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video