我想通过提供带有城市名称的API来获取城市的纬度和经度。它应该适用于大多数城市,无论用户如何输入城市。
例如:
城市可以是‘迈阿密,美国’或城市可以是‘迈阿密,美国’
如何打印它的纬度?
发布于 2012-06-22 09:41:05
您可以在以下位置找到jsfiddled代码:http://jsfiddle.net/YphZw/或以下代码:
$("#btn").click(function(){
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'miami, us'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
alert("Something got wrong " + status);
}
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
<input id="btn" type="button" value="search for miami coordinates" />
</body>
</html>
如果您想了解更多有关Javascript API的示例,请尝试此链接:https://developers.google.com/maps/documentation/javascript/examples/
我写的代码的灵感来自于geocoding-simple示例。
致以问候。
编辑1:
您可以使用非官方的PHP库来实现它。检查此示例:http://www.bradwedell.com/phpgooglemapapi/demos/geocoding.php (代码位于bottom=
发布于 2012-06-22 09:40:11
你可以使用谷歌的地理编码服务,例如,
http://maps.googleapis.com/maps/api/geocode/xml?address=Miami+FL&sensor=false
这为您提供了多种格式(JSON、XML等)的地理参考数据。在任何情况下,该位置肯定在返回的数据块中。
API文档位于:
发布于 2017-01-08 11:36:44
每条评论的更新如下:在2018年7月之后不工作。
这似乎是不必要的复杂。这是一个“附近事件”地图的例子。它将获取City, States,将它们转换为latLng坐标,并将标记放置在地图上:
// 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>StackOverflow请加入其他所有人的行列,并获得带有语法突出显示的GitHub标记...
https://stackoverflow.com/questions/11149144
复制相似问题