将 google 映射 div 动态添加到 DOM
Dynamically add google maps div into DOM
我想在动态添加到 DOM 的卡片中添加 Google 地图 API div、<div id="map"></div>
用户输入了搜索。作为测试,我可以将其附加到主 div 中,但不能在将卡插入 DOM.
后添加的卡中
代码如下。
const APIURL = 'https://restcountries.eu/rest/v2/name/'
const GOOGLE_MAPS_API = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDhlU1KMTlTh4C__bTJBxbVA-s7wvQbO9E&callback=initMap'
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
async function getCountryData(name) {
try {
const { data } = await axios.get(APIURL + name)
data.forEach(res => {
const countryData = res
addGMapsEl()
createCountryCard(countryData)
getLatLngPos(countryData)
} )
} catch (err) {
if(err.response.status == 404) {
createErrorCard('No countries found')
setTimeout(() => {
main.innerHTML = ''}
, 1500);
}
}
}
// Google Map API
function addGMapsEl() {
const script = document.createElement('script');
script.src = GOOGLE_MAPS_API;
script.defer = true;
document.head.appendChild(script);
const mapDiv = document.createElement('div')
mapDiv.id = 'map'
main.appendChild(mapDiv)
}
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 51, lng: 9},
zoom: 7
});
}
function createCountryCard(country) {
const cardHTML = `
<div class="content-container">
<div class="card">
<div class="wrapper">
<div class="card-title">
<h2>${country.name}</h2>
<h4>Capital: ${country.capital}</h4>
<h5>Population: ${country.population.toLocaleString('en')}</h5>
</div>
<div class="card-image">
<img
src="${country.flag}"
alt="${country.name +'-flag'}"
/>
</div>
</div>
<div class="wrapper">
<div class="map-content">
</div>
<div class="card-content">
<ul class="card-list">
<li><strong>Region:</strong> ${country.region}</li>
<li><strong>Subregion:</strong> ${country.subregion}</li>
<li><strong>Currency:</strong> ${country.currencies[0].name}<span> ${country.currencies[0].symbol}</span></li>
<li><strong>Spoken Language:</strong> ${country.languages[0].name}</li>
<li><strong>Timezone:</strong> ${country.timezones}</li>
</ul>
</div>
</div>
</div>
</div>
`
main.innerHTML += cardHTML
}
// Creates error card after no results found
function createErrorCard(msg) {
const cardHTML = `
<div class="card">
<h1>${msg}</h1>
</div>
`
main.innerHTML = cardHTML
}
// Clears the DOM on search
function clearDOM() {
main.innerHTML = ''
}
// Search Input
form.addEventListener('submit', (e) => {
e.preventDefault()
clearDOM()
const countryName = search.value
if(countryName) {
getCountryData(countryName)
search.value = ''
}
})
<body>
<div class="search-container">
<form id="form" class="form">
<input type="text" id="search" placeholder="Search for country..." />
</form>
</div>
<main id="main"></main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="script.js"></script>
</body>
我可以看到你常量中的 url 是错误的......正确的是:
'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap'
另一件事你永远不会调用 addGMapsEl()
函数来初始化地图。
最后 .card-content
元素没有出现在 DOM 上。
要在地图上显示国家/地区,您应该创建一个事件来处理
$(document).on("input", "#search", function(e){
//handle input information here
})
好的 - 所以 - 要创建 MAP,您需要使用 new google.maps.Map( ELEMENT_TO_CONTAIN_THE_MAP, MAP_OPTIONS)
,它在您的 mapInit
函数中。
您还应该只加载一次 API - 所以我在您的代码中做了一些改动...
我已从您的地图 url 中删除了 callback=initMap
- 因为您的元素在 google 的脚本是时不存在于 DOM 中加载。
然后在 createCountryCard
调用之后调用 mapInit
- 因为它将您的地图元素添加到 DOM - 现在我们可以将地图放在其中。
给定您的元素 id 参数 <div class="map-content" id="map-content">
。然后更改 mapInit
函数中的 id 以匹配您的元素 id,即 map-content
.
const APIURL = 'https://restcountries.eu/rest/v2/name/'
const GOOGLE_MAPS_API = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDhlU1KMTlTh4C__bTJBxbVA-s7wvQbO9E'
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
async function getCountryData(name) {
try {
const {
data
} = await axios.get(APIURL + name)
data.forEach(res => {
const countryData = res
//gmaps element is on card
createCountryCard(countryData);
initMap();
getLatLngPos(countryData)
})
} catch (err) {
if (err.response.status == 404) {
createErrorCard('No countries found')
setTimeout(() => {
main.innerHTML = ''
}, 1500);
}
}
}
// Google Map API
function addGMapsEl() {
const script = document.createElement('script');
script.src = GOOGLE_MAPS_API;
script.defer = true;
document.head.appendChild(script);
const mapDiv = document.createElement('div')
mapDiv.id = 'map'
main.appendChild(mapDiv)
}
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map-content"), {
center: {
lat: 51,
lng: 9
},
zoom: 7
});
}
function createCountryCard(country) {
const cardHTML = `
<div class="content-container">
<div class="card">
<div class="wrapper">
<div class="card-title">
<h2>${country.name}</h2>
<h4>Capital: ${country.capital}</h4>
<h5>Population: ${country.population.toLocaleString('en')}</h5>
</div>
<div class="card-image">
<img
src="${country.flag}"
alt="${country.name +'-flag'}"
/>
</div>
</div>
<div class="wrapper">
<div id="map-content" class="map-content">
</div>
<div class="card-content">
<ul class="card-list">
<li><strong>Region:</strong> ${country.region}</li>
<li><strong>Subregion:</strong> ${country.subregion}</li>
<li><strong>Currency:</strong> ${country.currencies[0].name}<span> ${country.currencies[0].symbol}</span></li>
<li><strong>Spoken Language:</strong> ${country.languages[0].name}</li>
<li><strong>Timezone:</strong> ${country.timezones}</li>
</ul>
</div>
</div>
</div>
</div>
`
main.innerHTML += cardHTML
}
// Creates error card after no results found
function createErrorCard(msg) {
const cardHTML = `
<div class="card">
<h1>${msg}</h1>
</div>
`
main.innerHTML = cardHTML
}
// Clears the DOM on search
function clearDOM() {
main.innerHTML = ''
}
// Search Input
form.addEventListener('submit', (e) => {
e.preventDefault()
clearDOM()
const countryName = search.value
if (countryName) {
getCountryData(countryName)
search.value = ''
}
})
addGMapsEl();
.map-content {
width: 100%;
height: 300px;
}
.card-image img {
max-height: 50px;
box-shadow: 1px 1px 5px #aaa;
}
<body>
<div class="search-container">
<form id="form" class="form">
<input type="text" id="search" placeholder="Search for country..." />
</form>
</div>
<main id="main"></main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="script.js"></script>
</body>
看起来现在可以使用了...您可能想稍后在您的地图上使用 setCenter
将视图移动到新位置 - 在 mapInit
之后执行此操作
还添加了一些 CSS - 为地图元素指定大小并缩小您拥有的巨大标志。
我想在动态添加到 DOM 的卡片中添加 Google 地图 API div、<div id="map"></div>
用户输入了搜索。作为测试,我可以将其附加到主 div 中,但不能在将卡插入 DOM.
代码如下。
const APIURL = 'https://restcountries.eu/rest/v2/name/'
const GOOGLE_MAPS_API = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDhlU1KMTlTh4C__bTJBxbVA-s7wvQbO9E&callback=initMap'
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
async function getCountryData(name) {
try {
const { data } = await axios.get(APIURL + name)
data.forEach(res => {
const countryData = res
addGMapsEl()
createCountryCard(countryData)
getLatLngPos(countryData)
} )
} catch (err) {
if(err.response.status == 404) {
createErrorCard('No countries found')
setTimeout(() => {
main.innerHTML = ''}
, 1500);
}
}
}
// Google Map API
function addGMapsEl() {
const script = document.createElement('script');
script.src = GOOGLE_MAPS_API;
script.defer = true;
document.head.appendChild(script);
const mapDiv = document.createElement('div')
mapDiv.id = 'map'
main.appendChild(mapDiv)
}
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 51, lng: 9},
zoom: 7
});
}
function createCountryCard(country) {
const cardHTML = `
<div class="content-container">
<div class="card">
<div class="wrapper">
<div class="card-title">
<h2>${country.name}</h2>
<h4>Capital: ${country.capital}</h4>
<h5>Population: ${country.population.toLocaleString('en')}</h5>
</div>
<div class="card-image">
<img
src="${country.flag}"
alt="${country.name +'-flag'}"
/>
</div>
</div>
<div class="wrapper">
<div class="map-content">
</div>
<div class="card-content">
<ul class="card-list">
<li><strong>Region:</strong> ${country.region}</li>
<li><strong>Subregion:</strong> ${country.subregion}</li>
<li><strong>Currency:</strong> ${country.currencies[0].name}<span> ${country.currencies[0].symbol}</span></li>
<li><strong>Spoken Language:</strong> ${country.languages[0].name}</li>
<li><strong>Timezone:</strong> ${country.timezones}</li>
</ul>
</div>
</div>
</div>
</div>
`
main.innerHTML += cardHTML
}
// Creates error card after no results found
function createErrorCard(msg) {
const cardHTML = `
<div class="card">
<h1>${msg}</h1>
</div>
`
main.innerHTML = cardHTML
}
// Clears the DOM on search
function clearDOM() {
main.innerHTML = ''
}
// Search Input
form.addEventListener('submit', (e) => {
e.preventDefault()
clearDOM()
const countryName = search.value
if(countryName) {
getCountryData(countryName)
search.value = ''
}
})
<body>
<div class="search-container">
<form id="form" class="form">
<input type="text" id="search" placeholder="Search for country..." />
</form>
</div>
<main id="main"></main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="script.js"></script>
</body>
我可以看到你常量中的 url 是错误的......正确的是:
'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap'
另一件事你永远不会调用 addGMapsEl()
函数来初始化地图。
最后 .card-content
元素没有出现在 DOM 上。
要在地图上显示国家/地区,您应该创建一个事件来处理
$(document).on("input", "#search", function(e){
//handle input information here
})
好的 - 所以 - 要创建 MAP,您需要使用 new google.maps.Map( ELEMENT_TO_CONTAIN_THE_MAP, MAP_OPTIONS)
,它在您的 mapInit
函数中。
您还应该只加载一次 API - 所以我在您的代码中做了一些改动...
我已从您的地图 url 中删除了 callback=initMap
- 因为您的元素在 google 的脚本是时不存在于 DOM 中加载。
然后在 createCountryCard
调用之后调用 mapInit
- 因为它将您的地图元素添加到 DOM - 现在我们可以将地图放在其中。
给定您的元素 id 参数 <div class="map-content" id="map-content">
。然后更改 mapInit
函数中的 id 以匹配您的元素 id,即 map-content
.
const APIURL = 'https://restcountries.eu/rest/v2/name/'
const GOOGLE_MAPS_API = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDhlU1KMTlTh4C__bTJBxbVA-s7wvQbO9E'
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
async function getCountryData(name) {
try {
const {
data
} = await axios.get(APIURL + name)
data.forEach(res => {
const countryData = res
//gmaps element is on card
createCountryCard(countryData);
initMap();
getLatLngPos(countryData)
})
} catch (err) {
if (err.response.status == 404) {
createErrorCard('No countries found')
setTimeout(() => {
main.innerHTML = ''
}, 1500);
}
}
}
// Google Map API
function addGMapsEl() {
const script = document.createElement('script');
script.src = GOOGLE_MAPS_API;
script.defer = true;
document.head.appendChild(script);
const mapDiv = document.createElement('div')
mapDiv.id = 'map'
main.appendChild(mapDiv)
}
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map-content"), {
center: {
lat: 51,
lng: 9
},
zoom: 7
});
}
function createCountryCard(country) {
const cardHTML = `
<div class="content-container">
<div class="card">
<div class="wrapper">
<div class="card-title">
<h2>${country.name}</h2>
<h4>Capital: ${country.capital}</h4>
<h5>Population: ${country.population.toLocaleString('en')}</h5>
</div>
<div class="card-image">
<img
src="${country.flag}"
alt="${country.name +'-flag'}"
/>
</div>
</div>
<div class="wrapper">
<div id="map-content" class="map-content">
</div>
<div class="card-content">
<ul class="card-list">
<li><strong>Region:</strong> ${country.region}</li>
<li><strong>Subregion:</strong> ${country.subregion}</li>
<li><strong>Currency:</strong> ${country.currencies[0].name}<span> ${country.currencies[0].symbol}</span></li>
<li><strong>Spoken Language:</strong> ${country.languages[0].name}</li>
<li><strong>Timezone:</strong> ${country.timezones}</li>
</ul>
</div>
</div>
</div>
</div>
`
main.innerHTML += cardHTML
}
// Creates error card after no results found
function createErrorCard(msg) {
const cardHTML = `
<div class="card">
<h1>${msg}</h1>
</div>
`
main.innerHTML = cardHTML
}
// Clears the DOM on search
function clearDOM() {
main.innerHTML = ''
}
// Search Input
form.addEventListener('submit', (e) => {
e.preventDefault()
clearDOM()
const countryName = search.value
if (countryName) {
getCountryData(countryName)
search.value = ''
}
})
addGMapsEl();
.map-content {
width: 100%;
height: 300px;
}
.card-image img {
max-height: 50px;
box-shadow: 1px 1px 5px #aaa;
}
<body>
<div class="search-container">
<form id="form" class="form">
<input type="text" id="search" placeholder="Search for country..." />
</form>
</div>
<main id="main"></main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="script.js"></script>
</body>
看起来现在可以使用了...您可能想稍后在您的地图上使用 setCenter
将视图移动到新位置 - 在 mapInit
还添加了一些 CSS - 为地图元素指定大小并缩小您拥有的巨大标志。