这似乎是不必要的复杂 . 这是一个示例"nearby events" map . 它将需要 City, State s,将它们转换为 latLng coords,并将标记放在 Map 上:
// Nearby Events with Google Maps
window.nearbyEventsMap = () => {
const centerOfUS = {
lat: 37.09024,
lng: -95.712891
}
// Create a map object and specify the DOM element for display.
const map = new google.maps.Map(document.querySelector('#nearby_events_map'), {
center: centerOfUS,
scrollwheel: false,
zoom: 4
})
// Create a marker and set its position.
const geocoder = new google.maps.Geocoder()
// Filter out duplicate cityStates
let cityStates = {}
document.querySelectorAll('.nearby_event_city_state').forEach(event => {
cityStates[event] = event.innerText
})
// `cityState` is in the format of "City, State". It's not picky about state being a word or the abbreviation.
for (const cityState in cityStates) {
const location = cityStates[cityState]
geocoder.geocode({
address: location
}, function (results, status) {
if (status === 'OK') {
const result = results[0].geometry.location
const lat = result.lat()
const lng = result.lng()
const latLng = {
lat,
lng
}
return new google.maps.Marker({
map: map,
position: latLng
})
}
})
}
}
// /Nearby Events with Google Maps
确保包含 <script> 标记 .
<script src="/dist/js/main.js"></script>
<!-- We're loading this after the main.js script so the callback from main.js will be available to it. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=nearbyEventsMap"></script>
3 回答
你可以在这里找到jsfiddled代码:http://jsfiddle.net/YphZw/或以下:
如果您需要更多Javascript API示例,请尝试以下链接:https://developers.google.com/maps/documentation/javascript/examples/
我写的代码的灵感来自地理编码简单的样本 .
问候 .
编辑1:
您可以使用非官方PHP库来实现它 . 检查此示例:http://www.bradwedell.com/phpgooglemapapi/demos/geocoding.php(代码位于底部=
您可以使用Google的地理编码服务,例如
http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false
这为您提供了各种格式(JSON,XML等)的地理配准数据 . 无论如何,该位置肯定在返回的数据块中 .
API文档位于:
https://developers.google.com/maps/documentation/geocoding/
Update per comment below: 在2018年7月之后不起作用 .
这似乎是不必要的复杂 . 这是一个示例"nearby events" map . 它将需要
City, State
s,将它们转换为latLng
coords,并将标记放在 Map 上:确保包含
<script>
标记 .StackOverflow请加入其他人并使用语法高亮获得GitHub markdown ...