gpt4 book ai didi

javascript - 使用 Google Maps Javascript API 从一组预定义位置获取最近的位置

转载 作者:行者123 更新时间:2023-11-29 19:30:13 26 4
gpt4 key购买 nike

我有一组 2 个预定义位置,根据用户输入的邮政编码,我需要显示最近的位置。

到目前为止,我已经使用邮政编码搜索了用户输入位置:

$("form#zipcodeSearch").on("submit", function(event){
event.preventDefault();
var jsonUrl = 'http://maps.googleapis.com/maps/api/geocode/json?address='+$("input#zipcode").val();

$.ajax({
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
dataType: "json",
url: jsonUrl,
success: function (data) {

var lat = (data.results[0].geometry.bounds.northeast.lat + data.results[0].geometry.bounds.southwest.lat) / 2;
var lng = (data.results[0].geometry.bounds.northeast.lng + data.results[0].geometry.bounds.southwest.lng) / 2;

initialize(lat, lng);

}
});

});

var map;
function initialize(lat, lng) {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);

// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(lat, lng);

var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: '<div style="width: 75px">You are here!</div>'
});

map.setCenter(pos);

}, function() {
handleNoGeolocation(true);
}, {
enableHighAccuracy: true
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}

function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}

var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};

var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
*{
margin: 0;
padding: 0;
}

body{
font-family: arial;
font-size: 62.5%; /* so, 10px = 1rem */
}

#map-canvas{
z-index: -1;
position: absolute;
top: 0;
height: 100%;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

<form id="zipcodeSearch">
<input type="text" id="zipcode" placeholder="Enter Zipcode"/>
<input type="submit" value="Search" />
</form>

<div id="map-canvas"></div>

jsFiddle

关于如何实现这一点有什么想法吗?如果 JS API 无法实现,是否有任何其他 API 可以帮助我实现这一目标?

编辑: Cleaned-up jsFiddle version

最佳答案

更新:
对 Google Maps Platform 的无 key 访问现已弃用。您的所有 API 调用都需要一个 API key ,以避免服务中断。更多详情请引用http://g.co/dev/maps-no-account


原答案:
我能够通过以下方式解决这个问题:

  1. 从此 URL 获取输入邮政编码的经纬度坐标: http://maps.googleapis.com/maps/api/geocode/json?address=zipcode(添加邮政编码)
  2. 取此 URL 响应中返回的东北和西南经纬度的平均值。考虑计算出的平均纬度和经度作为输入坐标。
  3. 使用 google.maps.geometry.spherical.computeDistanceBetween()
  4. 计算距离以获得最近的位置
  5. 使用所有标记初始化 Google map 。
  6. 使用 google.maps.LatLngBounds() 调整缩放比例,使 map 包含输入邮政编码的位置和最近的搜索位置。

这是一个演示。 H 图标代表输入的邮政编码位置,C 图标代表搜索到的最近的位置。 (目前,我只保留了 2 个预定义位置)。

var predefinedLocations = [{
"name": "Brookwood Medical Center",
"lat": 33.4636415,
"lng": -86.7771671
},
{
"name": "Lutheran Medical Center",
"lat": 40.646872,
"lng": -74.020892
}
];

$("form#zipcodeSearch").on("submit", function(event) {
event.preventDefault();
var jsonUrl = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + $("input#zipcode").val();

$.ajax({
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
dataType: "json",
url: jsonUrl,
success: function(data) {

var lat = (data.results[0].geometry.bounds.northeast.lat + data.results[0].geometry.bounds.southwest.lat) / 2;
var lng = (data.results[0].geometry.bounds.northeast.lng + data.results[0].geometry.bounds.southwest.lng) / 2;
var p1, p2;

predefinedLocations.forEach(function(obj) {
p1 = new google.maps.LatLng(obj.lat, obj.lng);
p2 = new google.maps.LatLng(lat, lng);

obj.distance = calcDistance(p1, p2);
});

// sort by distance
var locationInfo = predefinedLocations.sort(compare);

//console.log('locationInfo', locationInfo);

initializeGoogleMap(locationInfo, lat, lng);

}
});

});

var map;

function initializeGoogleMap(locationInfo, lat, lng) {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

// zoom to only the input zipcode and closest location
var latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend(new google.maps.LatLng(locationInfo[0].lat, locationInfo[0].lng));
latlngbounds.extend(new google.maps.LatLng(lat, lng));
map.fitBounds(latlngbounds);

var infowindow = new google.maps.InfoWindow();

var marker, i;

// set marker for input location
setMarker(lat, lng, map, 'http://www.lsac.org/images/default-source/mainportalimages/icon-h-grey-bg.jpg?sfvrsn=2', "You are here!", i, infowindow);

// set marker for closest location
setMarker(locationInfo[0].lat, locationInfo[0].lng, map, 'http://alert.mta.info/sites/all/themes/mta/images/subway_bullets/c.png', locationInfo[0].name, i, infowindow);

for (var j = 1; j < locationInfo.length; j++) {
// set marker for other location
setMarker(locationInfo[j].lat, locationInfo[j].lng, map, '', locationInfo[j].name, i, infowindow);
}

}

function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}

function compare(a, b) {
if (parseFloat(a.distance) < parseFloat(b.distance)) {
return -1;
}

if (parseFloat(a.distance) > parseFloat(b.distance)) {
return 1;
}

return 0;
}

function setMarker(lat, lng, map, icon, content, i, infowindow) {

var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
icon: icon
});

google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));

}
* {
margin: 0;
padding: 0;
}

html {
font-size: 62.5%;
/* so, 10px = 1rem */
}

body {
font-family: arial;
}

#map-canvas {
z-index: -1;
position: absolute;
top: 0;
height: 100%;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>

<form id="zipcodeSearch">
<input type="text" id="zipcode" placeholder="Enter zipcode here" />
<input type="submit" value="Search" />
</form>

<div id="map-canvas"></div>

jsFiddle version of the same code

我希望这个答案能帮助遇到与我相同问题的人。

关于javascript - 使用 Google Maps Javascript API 从一组预定义位置获取最近的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com