我正在尝试搜索里程半径内的所有供应商,但为了做到这一点,我需要我正在搜索的地址的坐标。预先获取这些坐标是不可行的,因为地图搜索并不经常使用。
所以,我想做的是在点击链接时从谷歌地图中获取坐标(如果我们还没有得到它们),然后继续使用默认的浏览器行为。这是我必须完成的代码:
HTML
<a href="/vendors/search" target="_blank" class="vendorMapSearch"
data-miles-radius="50" data-address="@Model.Address.SingleLine()"
data-customer-name="@Model.CustomerName" data-customer-id="@Model.CustomerId"
data-service-on="@Model.ServiceOn">Vendor Map Search</a>
JavaScript
$(document).on('click', 'a.vendorMapSearch', function (e) {
console.log('HANDLE CLICK');
var $target = $(e.target),
data = $target.data();
if (!data.latitude || !data.longitude) {
console.log('HITTING GOOGLE MAPS');
var url = 'https://maps.googleapis.com/maps/api/geocode/json?language=en&sensor=false&address=' + data.address;
$.getJSON(url, function (resp) {
console.log('response received');
if (!resp.results.length) {
$('<div>Could not find coordinates for the address entered.</div>');
return;
}
$target.data('latitude', resp.results[0].geometry.location.lat);
$target.data('longitude', resp.results[0].geometry.location.lng);
$target.attr('href', $target.attr('href') + '?' + $.param($target.data()));
$target.trigger('coordinatesAcquired');
});
return false;
}
console.log('RETURNING TRUE');
return true;
});
$(document).on('coordinatesAcquired', function() {
console.log('COORDINATES ACQUIRED');
$('a.vendorMapSearch').trigger('click');
});
它给出了这个输出:
HANDLE CLICK
HITTING GOOGLE MAPS
XHR finished loading: (blah blah)
COORDINATES ACQUIRED
HANDLE CLICK
RETURNING TRUE
它看起来对我来说是正确的,但行为是它不会触发默认链接浏览器行为(至少在 Chrome 中),除非我再次单击该链接。有谁知道这是怎么回事?