<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>🌍 真实地理城市生成器</title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
<!-- PDF 导出 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<!-- 图表支持 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Noto Sans SC', 'Roboto', sans-serif;
background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
color: #fff;
min-height: 100vh;
padding: 20px;
background-attachment: fixed;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
header {
text-align: center;
margin-bottom: 25px;
}
h1 {
font-size: 2.8em;
margin-bottom: 8px;
background: linear-gradient(90deg, #ffd166, #06d6a0);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 0 2px 10px rgba(0,0,0,0.2);
}
.subtitle {
font-size: 1.2em;
opacity: 0.9;
margin-bottom: 15px;
}
.controls {
display: flex;
justify-content: center;
gap: 15px;
flex-wrap: wrap;
margin: 20px auto;
}
button {
padding: 12px 24px;
font-size: 1.05em;
border: none;
border-radius: 50px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.btn-generate { background: linear-gradient(45deg, #ff6b6b, #ff8e53); color: white; }
.btn-print { background: linear-gradient(45deg, #4ecdc4, #1a936f); color: white; }
.btn-pdf { background: linear-gradient(45deg, #45b7d1, #2980b9); color: white; }
.btn-data { background: linear-gradient(45deg, #96ceb4, #6ab04c); color: white; }
button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}
.loading {
text-align: center;
font-size: 1.2em;
margin: 20px 0;
color: #ffd166;
display: none;
}
.city-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
gap: 30px;
margin-top: 20px;
}
@media (max-width: 600px) {
.city-container { grid-template-columns: 1fr; }
.controls { flex-direction: column; align-items: center; }
}
.info-panel {
background: rgba(255, 255, 255, 0.08);
backdrop-filter: blur(12px);
border-radius: 18px;
padding: 25px;
box-shadow: 0 10px 30px rgba(0,0,0,0.25);
border: 1px solid rgba(255,255,255,0.1);
}
.info-panel h2 {
font-size: 1.6em;
margin-bottom: 20px;
color: #ffd166;
border-bottom: 2px solid #ffd166;
padding-bottom: 8px;
display: flex;
align-items: center;
gap: 10px;
}
.info-item {
margin: 14px 0;
line-height: 1.6;
font-size: 1.05em;
}
.info-item i {
width: 30px;
color: #a29bfe;
}
.map-container {
text-align: center;
margin: 30px 0;
}
.map-container h2 {
margin-bottom: 15px;
color: #06d6a0;
}
#real-map {
width: 100%;
height: 500px;
border: 2px solid rgba(255,255,255,0.2);
border-radius: 12px;
background: #1a1a2e;
overflow: hidden;
position: relative;
}
.chart-container {
width: 100%;
height: 300px;
margin-top: 20px;
}
.timeline {
margin-top: 25px;
position: relative;
padding-left: 30px;
}
.timeline::before {
content: '';
position: absolute;
left: 15px;
top: 0;
bottom: 0;
width: 4px;
background: #ffd166;
border-radius: 2px;
}
.timeline-item {
margin-bottom: 20px;
position: relative;
}
.timeline-item::before {
content: '';
position: absolute;
left: -27px;
top: 8px;
width: 16px;
height: 16px;
border-radius: 50%;
background: #4ecdc4;
border: 3px solid #1a1a2e;
}
.timeline-year {
font-weight: bold;
color: #ffd166;
}
footer {
text-align: center;
margin-top: 50px;
opacity: 0.75;
font-size: 0.95em;
}
@media print {
.controls, .loading, footer, header button { display: none !important; }
body { background: white; color: black; }
.info-panel { background: white !important; color: black !important; }
}
</style>
</head>
<body>
<!-- 音效 -->
<audio id="bgMusic" loop>
<source src="https://www.soundjay.com/misc/sounds/bell-ringing-05.mp3" type="audio/mpeg">
</audio>
<audio id="clickSound">
<source src="https://www.soundjay.com/buttons/sounds/button-1.mp3" type="audio/mpeg">
</audio>
<audio id="mapClickSound">
<source src="https://www.soundjay.com/buttons/sounds/button-09.mp3" type="audio/mpeg">
</audio>
<div class="container">
<header>
<h1><i class="fas fa-globe-asia"></i> 真实地理城市生成器</h1>
<p class="subtitle">生成具有真实地理、行政区划、历史时间轴的虚构城市</p>
<div class="controls">
<button id="generateBtn" class="btn-generate">
<i class="fas fa-magic"></i> 生成城市
</button>
<button id="printBtn" class="btn-print">
<i class="fas fa-print"></i> 打印报告
</button>
<button id="exportPdfBtn" class="btn-pdf">
<i class="fas fa-file-pdf"></i> 导出 PDF
</button>
<button id="exportDataBtn" class="btn-data">
<i class="fas fa-file-csv"></i> 导出人口数据
</button>
<button id="toggleMusic" class="btn-generate">
<i class="fas fa-music"></i> 音乐:开
</button>
</div>
<div class="loading" id="loading">🌍 正在生成城市数据...</div>
</header>
<div id="output" style="display: none;">
<div class="city-container">
<!-- 左侧:城市信息 -->
<div class="info-panel">
<h2><i class="fas fa-city"></i> 城市概况</h2>
<div class="info-item"><i class="fas fa-tag"></i> <strong>城市名称:</strong> <span id="cityName"></span></div>
<div class="info-item"><i class="fas fa-globe-americas"></i> <strong>国家:</strong> <span id="country"></span></div>
<div class="info-item"><i class="fas fa-map-marker-alt"></i> <strong>地理位置:</strong> <span id="location"></span></div>
<div class="info-item"><i class="fas fa-mountain"></i> <strong>地形:</strong> <span id="terrain"></span></div>
<div class="info-item"><i class="fas fa-thermometer-half"></i> <strong>气候类型:</strong> <span id="climate"></span></div>
<div class="info-item"><i class="fas fa-sun"></i> <strong>年均温:</strong> <span id="avgTemp"></span></div>
<div class="info-item"><i class="fas fa-cloud"></i> <strong>当前天气:</strong> <span id="weather"></span></div>
<div class="info-item"><i class="fas fa-users"></i> <strong>人口:</strong> <span id="population"></span></div>
<div class="info-item"><i class="fas fa-ruler-combined"></i> <strong>面积:</strong> <span id="area"></span> km²</div>
<div class="info-item"><i class="fas fa-weight-hanging"></i> <strong>人口密度:</strong> <span id="density"></span> 人/km²</div>
<div class="info-item"><i class="fas fa-calendar-alt"></i> <strong>建市年份:</strong> <span id="founded"></span></div>
<div class="info-item"><i class="fas fa-quote-left"></i> <strong>城市口号:</strong> <span id="motto"></span></div>
<div class="info-item"><i class="fas fa-star"></i> <strong>昵称:</strong> <span id="nickname"></span></div>
<div class="info-item"><i class="fas fa-water"></i> <strong>主要河流:</strong> <span id="river"></span></div>
</div>
<!-- 右侧:经济与政府 -->
<div class="info-panel">
<h2><i class="fas fa-chart-line"></i> 经济与政府</h2>
<div class="info-item"><i class="fas fa-industry"></i> <strong>支柱产业:</strong> <span id="industry"></span></div>
<div class="info-item"><i class="fas fa-dollar-sign"></i> <strong>GDP(总量):</strong> <span id="gdp"></span> 亿美元</div>
<div class="info-item"><i class="fas fa-hand-holding-usd"></i> <strong>人均GDP:</strong> <span id="perCapitaGDP"></span> 美元</div>
<div class="info-item"><i class="fas fa-percentage"></i> <strong>失业率:</strong> <span id="unemployment"></span></div>
<div class="info-item"><i class="fas fa-balance-scale"></i> <strong>税收率:</strong> <span id="taxRate"></span></div>
<div class="info-item"><i class="fas fa-skull-crossbones"></i> <strong>犯罪率:</strong> <span id="crimeRate"></span></div>
<div class="info-item"><i class="fas fa-tree"></i> <strong>绿化率:</strong> <span id="greenRate"></span></div>
<h2 style="margin-top: 20px;"><i class="fas fa-user-tie"></i> 政府高层</h2>
<div class="info-item"><i class="fas fa-user"></i> <strong>市长:</strong> <span id="mayor"></span></div>
<div class="info-item"><i class="fas fa-user-friends"></i> <strong>副市长:</strong> <span id="viceMayor"></span></div>
<div class="info-item"><i class="fas fa-users-cog"></i> <strong>党派:</strong> <span id="party"></span></div>
<div class="info-item"><i class="fas fa-calendar-check"></i> <strong>任期:</strong> <span id="term"></span></div>
<div class="info-item"><i class="fas fa-shield-alt"></i> <strong>警察局长:</strong> <span id="policeChief"></span></div>
<div class="info-item"><i class="fas fa-money-bill-wave"></i> <strong>财政局长:</strong> <span id="financeChief"></span></div>
<div class="info-item"><i class="fas fa-drafting-compass"></i> <strong>规划局长:</strong> <span id="planningChief"></span></div>
</div>
</div>
<!-- 中下:历史与人口 -->
<div class="city-container">
<div class="info-panel">
<h2><i class="fas fa-book"></i> 历史时间轴</h2>
<div class="timeline" id="historyTimeline"></div>
</div>
<div class="info-panel">
<h2><i class="fas fa-democrat"></i> 人口结构</h2>
<div class="info-item"><i class="fas fa-venus-mars"></i> <strong>性别比:</strong> <span id="genderRatio"></span></div>
<div class="info-item"><i class="fas fa-baby"></i> <strong>出生率:</strong> <span id="birthRate"></span></div>
<div class="info-item"><i class="fas fa-skull"></i> <strong>死亡率:</strong> <span id="deathRate"></span></div>
<div class="info-item"><i class="fas fa-heartbeat"></i> <strong>平均寿命:</strong> <span id="lifeExpectancy"></span></div>
<div class="info-item"><i class="fas fa-plane-arrival"></i> <strong>移民率:</strong> <span id="migration"></span></div>
<div class="info-item"><i class="fas fa-user-graduate"></i> <strong>教育水平:</strong> <span id="education"></span></div>
<div class="info-item"><i class="fas fa-layer-group"></i> <strong>年龄分布:</strong> <span id="ageDist"></span></div>
<h2 style="margin-top: 20px;"><i class="fas fa-building"></i> 科技公司</h2>
<div id="companies"></div>
</div>
</div>
<!-- 图表 -->
<div class="info-panel">
<h2><i class="fas fa-chart-pie"></i> 人口年龄结构</h2>
<div class="chart-container">
<canvas id="ageChart"></canvas>
</div>
</div>
<!-- 真实地图 -->
<div class="info-panel map-container">
<h2><i class="fas fa-map"></i> 城市地理地图</h2>
<div id="real-map"></div>
<p><small>📌 点击地图查看区域详情</small></p>
</div>
</div>
<footer>
真实地理城市生成器 v5.0 | 数据完全虚构 | 支持打印、导出、图表 | 使用 HTML/CSS/JS 构建
</footer>
</div>
<script>
// ======================
// 音效控制
// ======================
const bgMusic = document.getElementById('bgMusic');
const clickSound = document.getElementById('clickSound');
const mapClickSound = document.getElementById('mapClickSound');
const toggleMusicBtn = document.getElementById('toggleMusic');
let musicOn = true;
toggleMusicBtn.addEventListener('click', () => {
musicOn = !musicOn;
if (musicOn) {
bgMusic.play().catch(e => console.log("音乐播放被阻止"));
toggleMusicBtn.innerHTML = '<i class="fas fa-music"></i> 音乐:开';
} else {
bgMusic.pause();
toggleMusicBtn.innerHTML = '<i class="fas fa-music"></i> 音乐:关';
}
});
function playClick() {
if (musicOn) {
clickSound.currentTime = 0;
clickSound.play().catch(() => {});
}
}
function playMapClick() {
if (musicOn) {
mapClickSound.currentTime = 0;
mapClickSound.play().catch(() => {});
}
}
// ======================
// 数据词库
// ======================
const CITY_PREFIXES = ["新", "港", "湖", "北", "南", "东", "西", "堡", "大", "春", " mills", "岩", "山", "阳", "湾"];
const CITY_SUFFIXES = ["市", "城", "堡", "港", "镇", "区", "谷", "岛", "滩", "岭"];
const COUNTRIES = ["美国", "加拿大", "英国", "德国", "法国", "澳大利亚", "瑞典", "挪威", "奥地利", "瑞士"];
const TERRAINS = ["沿海平原", "内陆丘陵", "山区", "河谷", "岛屿", "沙漠边缘", "森林地带"];
const CLIMATES = [
{ name: "温带季风气候", temp: "8-15°C" },
{ name: "地中海气候", temp: "12-20°C" },
{ name: "大陆性气候", temp: "1-25°C" },
{ name: "干旱气候", temp: "18-35°C" },
{ name: "亚热带湿润气候", temp: "15-28°C" },
{ name: "海洋性气候", temp: "10-18°C" }
];
const WEATHERS = ["晴天", "多云", "雨天", "雪天", "雾天", "暴风雨"];
const INDUSTRIES = ["科技", "制造业", "旅游业", "教育", "医疗", "农业", "金融", "新能源", "娱乐", "物流"];
const MOTTOES = ["团结进步", "创新与传统", "自然与城市交融", "为明天而建", "安全、强大、可持续"];
const NICKNAMES = ["翡翠之城", "河畔明珠", "北方硅谷", "山谷之心", "双湖之城"];
const NAMES_MALE = ["詹姆斯", "约翰", "罗伯特", "迈克尔", "威廉", "大卫"];
const NAMES_FEMALE = ["玛丽", "帕特里夏", "詹妮弗", "琳达", "伊丽莎白", "芭芭拉"];
const SURNAMES = ["史密斯", "约翰逊", "威廉姆斯", "布朗", "琼斯", "加西亚"];
const PARTIES = ["进步党", "保守党", "自由党", "绿党", "独立党", "团结党"];
const HISTORICAL_EVENTS = [
"{year}年发生大火,市中心被毁,后以装饰艺术风格重建。",
"{year}年由欧洲移民建立为贸易港口。",
"{year}年举办全国运动会,旅游业大发展。",
"{year}年代科技产业兴起,经济转型。",
"{year}年遭遇大洪水,建设新防洪系统。",
"著名作家{name}于{year}年在此出生。",
"{year}年宣布碳中和城市目标。",
"{year}年建成地标建筑{landmark}。",
"{year}年开通地铁系统,交通改善。",
"{year}年发现地下温泉,发展康养产业。"
];
const LANDMARKS = ["中央塔", "遗产大桥", "观景台", "老教堂", "科技中心", "城市公园"];
const RIVERS = ["清水河", "金沙江", "碧波河", "银溪", "蓝湾河", "翡翠川", "阳光河"];
const COMPANIES = [
{ name: "新星科技", industry: "人工智能", employees: "15,000" },
{ name: "蓝海集团", industry: "新能源", employees: "8,500" },
{ name: "云端数据", industry: "云计算", employees: "12,000" },
{ name: "绿源生物", industry: "生物科技", employees: "6,200" },
{ name: "智联制造", industry: "智能制造", employees: "22,000" }
];
// ======================
// 工具函数
// ======================
function rand(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
function randName() { return (Math.random() > 0.5 ? rand(NAMES_MALE) : rand(NAMES_FEMALE)) + " " + rand(SURNAMES); }
function randFloat(min, max) { return parseFloat((Math.random() * (max - min) + min).toFixed(2)); }
function randInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
// ======================
// 生成城市
// ======================
function generateCity() {
const city = {};
city.name = rand(CITY_PREFIXES) + rand(CITY_SUFFIXES);
city.country = rand(COUNTRIES);
city.latitude = randFloat(20, 50).toFixed(4);
city.longitude = randFloat(-120, -70).toFixed(4);
city.location = `${city.latitude}°N, ${city.longitude}°E`;
city.terrain = rand(TERRAINS);
city.climateObj = rand(CLIMATES);
city.climate = city.climateObj.name;
city.avgTemp = city.climateObj.temp;
city.weather = rand(WEATHERS);
city.population = randInt(50000, 3000000);
city.area = randFloat(100, 2000);
city.density = (city.population / city.area).toFixed(1);
city.founded = randInt(1750, 1980);
city.motto = rand(MOTTOES);
city.nickname = rand(NICKNAMES);
city.river = rand(RIVERS);
city.industry = rand(INDUSTRIES);
city.gdpTotal = (city.population * randFloat(40000, 90000) / 1e8).toFixed(1);
city.perCapitaGDP = randInt(40000, 100000);
city.unemployment = randFloat(2, 10).toFixed(1) + "%";
city.taxRate = randFloat(8, 25).toFixed(1) + "%";
city.crimeRate = ["低", "中等", "高"][randInt(0, 2)];
city.greenRate = randFloat(25, 65).toFixed(1) + "%";
city.mayor = randName();
city.viceMayor = randName();
city.party = rand(PARTIES);
city.term = `${randInt(2020, 2024)} - ${randInt(2024, 2028)}`;
city.policeChief = randName();
city.financeChief = randName();
city.planningChief = randName();
city.genderRatio = randInt(95, 105) + ":100";
city.birthRate = randFloat(8, 16).toFixed(1) + "‰";
city.deathRate = randFloat(6, 12).toFixed(1) + "‰";
city.lifeExpectancy = randInt(75, 85) + " 岁";
city.migration = ["净流入", "净流出", "平衡"][randInt(0, 2)];
city.education = ["高", "中等", "发展中"][randInt(0, 2)];
const a = randInt(15, 20), b = randInt(10, 15), c = randInt(35, 45), d = randInt(8, 12), e = 100 - a - b - c - d;
city.ageDist = `0-14: ${a}%, 15-24: ${b}%, 25-54: ${c}%, 55-64: ${d}%, 65+: ${e}%`;
// 历史事件
city.history = [];
const usedYears = new Set();
for (let i = 0; i < 5; i++) {
let event = rand(HISTORICAL_EVENTS);
let year = randInt(1700, 2023);
while (usedYears.has(year)) year = randInt(1700, 2023);
usedYears.add(year);
event = event.replace("{year}", year);
event = event.replace("{name}", randName());
event = event.replace("{landmark}", rand(LANDMARKS));
city.history.push({ year, event });
}
city.history.sort((a, b) => a.year - b.year);
// 科技公司
city.companies = [];
const companyCount = randInt(2, 4);
for (let i = 0; i < companyCount; i++) {
const comp = rand(COMPANIES);
city.companies.push({
name: comp.name,
industry: comp.industry,
employees: randInt(5000, 25000).toLocaleString()
});
}
return city;
}
// ======================
// 渲染城市
// ======================
function renderCity(city) {
document.getElementById('cityName').textContent = city.name;
document.getElementById('country').textContent = city.country;
document.getElementById('location').textContent = city.location;
document.getElementById('terrain').textContent = city.terrain;
document.getElementById('climate').textContent = city.climate;
document.getElementById('avgTemp').textContent = city.avgTemp;
document.getElementById('weather').textContent = city.weather;
document.getElementById('population').textContent = city.population.toLocaleString();
document.getElementById('area').textContent = city.area.toFixed(1);
document.getElementById('density').textContent = city.density;
document.getElementById('founded').textContent = city.founded;
document.getElementById('motto').textContent = `"${city.motto}"`;
document.getElementById('nickname').textContent = city.nickname;
document.getElementById('river').textContent = city.river;
document.getElementById('industry').textContent = city.industry;
document.getElementById('gdp').textContent = city.gdpTotal;
document.getElementById('perCapitaGDP').textContent = city.perCapitaGDP.toLocaleString();
document.getElementById('unemployment').textContent = city.unemployment;
document.getElementById('taxRate').textContent = city.taxRate;
document.getElementById('crimeRate').textContent = city.crimeRate;
document.getElementById('greenRate').textContent = city.greenRate;
document.getElementById('mayor').textContent = city.mayor;
document.getElementById('viceMayor').textContent = city.viceMayor;
document.getElementById('party').textContent = city.party;
document.getElementById('term').textContent = city.term;
document.getElementById('policeChief').textContent = city.policeChief;
document.getElementById('financeChief').textContent = city.financeChief;
document.getElementById('planningChief').textContent = city.planningChief;
document.getElementById('genderRatio').textContent = city.genderRatio;
document.getElementById('birthRate').textContent = city.birthRate;
document.getElementById('deathRate').textContent = city.deathRate;
document.getElementById('lifeExpectancy').textContent = city.lifeExpectancy;
document.getElementById('migration').textContent = city.migration;
document.getElementById('education').textContent = city.education;
document.getElementById('ageDist').textContent = city.ageDist;
// 历史时间轴
const timeline = document.getElementById('historyTimeline');
timeline.innerHTML = '';
city.history.forEach(item => {
const div = document.createElement('div');
div.className = 'timeline-item';
div.innerHTML = `<div class="timeline-year">${item.year}年</div><div>${item.event}</div>`;
timeline.appendChild(div);
});
// 科技公司
const companies = document.getElementById('companies');
companies.innerHTML = '';
city.companies.forEach(comp => {
const div = document.createElement('div');
div.className = 'info-item';
div.innerHTML = `<i class="fas fa-building"></i> <strong>${comp.name}</strong> - ${comp.industry}行业,员工${comp.employees}人`;
companies.appendChild(div);
});
// 图表
const ctx = document.getElementById('ageChart').getContext('2d');
if (window.ageChartInstance) window.ageChartInstance.destroy();
const ageData = city.ageDist.match(/(\d+)%/g).map(x => parseInt(x));
window.ageChartInstance = new Chart(ctx, {
type: 'pie',
data: {
labels: ['0-14岁', '15-24岁', '25-54岁', '55-64岁', '65+岁'],
datasets: [{
data: ageData,
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF']
}]
},
options: {
responsive: true,
plugins: {
legend: { position: 'right' }
}
}
});
// 真实地图
renderMap(city);
window.generatedCity = city;
}
// ======================
// 渲染真实地图(SVG)
// ======================
function renderMap(city) {
const mapContainer = document.getElementById('real-map');
mapContainer.innerHTML = '';
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
svg.setAttribute("viewBox", "0 0 800 600");
// 背景地形
const terrain = city.terrain;
let bgColor = "#4a9c6d"; // 默认绿色
if (terrain.includes("沙漠")) bgColor = "#d4b483";
else if (terrain.includes("山区")) bgColor = "#8d6e63";
else if (terrain.includes("沿海")) bgColor = "#4db6ac";
else if (terrain.includes("岛屿")) bgColor = "#aed581";
const bg = document.createElementNS(svgNS, "rect");
bg.setAttribute("width", "100%");
bg.setAttribute("height", "100%");
bg.setAttribute("fill", bgColor);
svg.appendChild(bg);
// 河流
if (Math.random() > 0.3) {
const river = document.createElementNS(svgNS, "path");
river.setAttribute("d", "M 100 300 Q 400 250 700 300");
river.setAttribute("stroke", "#2196f3");
river.setAttribute("stroke-width", "8");
river.setAttribute("fill", "none");
river.setAttribute("stroke-linecap", "round");
svg.appendChild(river);
}
// 城市边界
const boundary = document.createElementNS(svgNS, "path");
boundary.setAttribute("d", "M 200 150 L 600 150 L 600 450 L 200 450 Z");
boundary.setAttribute("fill", "none");
boundary.setAttribute("stroke", "#ffffff");
boundary.setAttribute("stroke-width", "3");
boundary.setAttribute("stroke-dasharray", "10,5");
svg.appendChild(boundary);
// 行政区划
const districts = [
{ name: "市中心", x: 350, y: 250, color: "#ff9800" },
{ name: "住宅区", x: 250, y: 200, color: "#9c27b0" },
{ name: "工业区", x: 500, y: 350, color: "#f44336" },
{ name: "商业区", x: 400, y: 300, color: "#00bcd4" },
{ name: "教育区", x: 300, y: 350, color: "#4caf50" }
];
districts.forEach(district => {
const rect = document.createElementNS(svgNS, "rect");
rect.setAttribute("x", district.x);
rect.setAttribute("y", district.y);
rect.setAttribute("width", "80");
rect.setAttribute("height", "60");
rect.setAttribute("fill", district.color);
rect.setAttribute("stroke", "#ffffff");
rect.setAttribute("stroke-width", "2");
rect.setAttribute("rx", "8");
rect.setAttribute("ry", "8");
rect.style.cursor = "pointer";
rect.addEventListener('click', () => {
playMapClick();
alert(`区域:${district.name}\n点击查看详情功能待开发`);
});
svg.appendChild(rect);
const text = document.createElementNS(svgNS, "text");
text.setAttribute("x", district.x + 40);
text.setAttribute("y", district.y + 35);
text.setAttribute("text-anchor", "middle");
text.setAttribute("fill", "white");
text.setAttribute("font-size", "12");
text.setAttribute("font-family", "'Noto Sans SC', sans-serif");
text.textContent = district.name;
svg.appendChild(text);
});
// 城市标记
const cityMarker = document.createElementNS(svgNS, "circle");
cityMarker.setAttribute("cx", "400");
cityMarker.setAttribute("cy", "300");
cityMarker.setAttribute("r", "12");
cityMarker.setAttribute("fill", "#ffeb3b");
cityMarker.setAttribute("stroke", "#000");
cityMarker.setAttribute("stroke-width", "2");
svg.appendChild(cityMarker);
const cityName = document.createElementNS(svgNS, "text");
cityName.setAttribute("x", "400");
cityName.setAttribute("y", "280");
cityName.setAttribute("text-anchor", "middle");
cityName.setAttribute("fill", "white");
cityName.setAttribute("font-size", "16");
cityName.setAttribute("font-family", "'Noto Sans SC', sans-serif");
cityName.setAttribute("font-weight", "bold");
cityName.textContent = city.name;
svg.appendChild(cityName);
mapContainer.appendChild(svg);
}
// ======================
// 导出功能
// ======================
document.getElementById('printBtn').addEventListener('click', () => {
playClick();
window.print();
});
document.getElementById('exportPdfBtn').addEventListener('click', async () => {
playClick();
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const element = document.body;
doc.setFont('Helvetica');
doc.setFontSize(12);
doc.text("城市报告 - " + (window.generatedCity?.name || "未知城市"), 20, 20);
await html2canvas(element, { scale: 1.5, useCORS: true }).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 190;
const imgHeight = canvas.height * imgWidth / canvas.width;
doc.addImage(imgData, 'PNG', 10, 30, imgWidth, imgHeight);
doc.save(`城市_${window.generatedCity.name}.pdf`);
});
});
document.getElementById('exportDataBtn').addEventListener('click', () => {
playClick();
const city = window.generatedCity;
const csv = [
["数据项", "数值"],
["城市名称", city.name],
["国家", city.country],
["人口", city.population],
["面积_km2", city.area],
["人口密度", city.density],
["GDP_亿美元", city.gdpTotal],
["人均GDP", city.perCapitaGDP],
["失业率", city.unemployment],
["出生率_‰", city.birthRate.replace('‰','')],
["死亡率_‰", city.deathRate.replace('‰','')],
["平均寿命_岁", city.lifeExpectancy.replace(' 岁','')],
["性别比", city.genderRatio],
["移民率", city.migration],
["教育水平", city.education],
["0-14岁比例", city.ageDist.match(/0-14: (\d+)%/)?.[1] || 0],
["15-24岁比例", city.ageDist.match(/15-24: (\d+)%/)?.[1] || 0],
["25-54岁比例", city.ageDist.match(/25-54: (\d+)%/)?.[1] || 0],
["55-64岁比例", city.ageDist.match(/55-64: (\d+)%/)?.[1] || 0],
["65+岁比例", city.ageDist.match(/65\+: (\d+)%/)?.[1] || 0],
].map(row => row.join(',')).join('\n');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", `城市人口数据_${city.name}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
// ======================
// 生成事件
// ======================
document.getElementById('generateBtn').addEventListener('click', function() {
playClick();
const loading = document.getElementById('loading');
const output = document.getElementById('output');
loading.style.display = 'block';
output.style.display = 'none';
setTimeout(() => {
const city = generateCity();
renderCity(city);
loading.style.display = 'none';
output.style.display = 'block';
}, 800);
});
window.onload = () => {
bgMusic.play().catch(() => console.log("自动播放被阻止"));
document.getElementById('generateBtn').click();
};
</script>
</body>
</html>
index.html
index.html