Skip to content

Instantly share code, notes, and snippets.

@cstriuli
Created November 25, 2020 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cstriuli/d659c144e8243c302fd156aed4270ab5 to your computer and use it in GitHub Desktop.
Save cstriuli/d659c144e8243c302fd156aed4270ab5 to your computer and use it in GitHub Desktop.
var mapInstance;
var autocompleteInstance;
var results = [];
var markers = [];
var infoWindows = [];
var markerIcon = null;
function initMap() {
markerIcon = new BMap.Icon("https://49f44b141764baa2639d-7ed4c224bc1671c64dae8740f0861232.ssl.cf6.rackcdn.com/assets/images/marker_lion.png", new BMap.Size(40, 45), {
imageSize: new BMap.Size(40, 45),
imageOffset: new BMap.Size(0, 0),
anchor: new BMap.Size(40 / 2, 0)
});
mapInstance = new BMap.Map('map', {
minZoom: 6,
maxZoom: 22,
});
mapInstance.addControl(new BMap.NavigationControl());
mapInstance.addControl(new BMap.ScaleControl());
mapInstance.centerAndZoom(new BMap.Point(103.56, 36.71), 5);
initAutocomplete();
bindEvents();
bindLocateSubmit();
bindNearbySubmit();
$('#locate').click();
}
function initAutocomplete() {
autocompleteInstance = new BMap.Autocomplete({
input: 'address',
location: mapInstance,
// types: ['city']
});
autocompleteInstance.addEventListener('onconfirm', function (e) {
var place = e.item.value;
var full_address = place.province + place.city + place.district + place.street + place.business;
mapInstance.clearOverlays();
var onSearchComplete = function () {
var results = local.getResults();
if(!results || !results.getPoi(0).point) {
alert("Autocomplete's returned place contains no geometry");
return;
}
var location = results.getPoi(0).point;
$('#lat').val(location.lat);
$('#lng').val(location.lng);
}
var local = new BMap.LocalSearch(mapInstance, {
onSearchComplete: onSearchComplete
});
local.search(full_address);
});
}
function bindNearbySubmit() {
var nearby = $('#nearby');
var enabled = false;
if(navigator.geolocation) {
nearby.prop('disabled', false);
enabled = true;
}
nearby.on('click', function (event) {
event.preventDefault();
if(enabled === false) return;
nearby.prop('disabled', true);
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function (r) {
if(this.getStatus() == BMAP_STATUS_SUCCESS) {
nearby.prop('disabled', false);
$("#address").val(r.address.province + ', ' + r.address.city + ', ' + r.address.street);
$('#lat').val(r.point.lat);
$('#lng').val(r.point.lng);
$('#locate').click();
} else {
nearby.prop('disabled', false);
alert('Geocode was not successful for the following reason: ' + this.getStatus());
}
}, {
timeout: 70000,
enableHighAccuracy: true,
maximumAge: 75000
})
});
}
function bindEvents() {
$(document).on('click', '.infowindow-content .infowindow-title', function (event) {
var index = $(this).parent().data('index');
var marker = markers[index];
var infowindow = infoWindows[index];
$('.infowindow-content').removeClass('active');
closeAllInfowindows();
marker.openInfoWindow(infowindow);
mapInstance.setCenter(marker.point);
$('.infowindow-content').filter(function () {
return $(this).data('index') == index
}).addClass('active');
});
$(document).on('click', '[data-zoom]', function (event) {
event.preventDefault();
var index = $(this).data('zoom');
var marker = markers[index];
mapInstance.centerAndZoom(marker.point, 15);
});
}
function bindLocateSubmit() {
$('#form-map').on('submit', function (event) {
event.preventDefault();
return;
});
$('#locate').on('click', function (event) {
event.preventDefault();
var self = $(this);
self.prop('disabled', true);
$('#waiting').fadeIn();
resetForm();
$.getJSON(self.data('url'), {
ajax: true,
value: $('#address').val(),
country: 'CN',
category: $('#category').val(),
radius: $('#address').val().length > 0 ? 50 : 'no_distance',
lat: $('#lat').val(),
lng: $('#lng').val(),
}, function (data) {
$('.results').html('');
$('#waiting').fadeOut();
for(var i = 0; i < data.length; i++) {
addMarker(data[i], i);
addResult(data[i], i);
}
if(markers.length > 0) {
setCenterByPoints();
} else {
alert($_words['no_dealers_found']);
}
self.prop('disabled', false);
});
});
}
function setCenterByPoints() {
var points = [];
for(var i = 0; i < markers.length; i++) {
points.push(markers[i].point);
}
mapInstance.setViewport(points);
}
function resetForm() {
markers.forEach(function (marker, index) {
markers[index].closeInfoWindow();
mapInstance.removeOverlay(marker);
});
infoWindows = [];
markers = [];
results = [];
}
function closeAllInfowindows() {
infoWindows.forEach(function (info, index) {
markers[index].closeInfoWindow();
});
}
function addMarker(data, index) {
var point = new BMap.Point(data.lng, data.lat);
if(isNaN(point.lat) || isNaN(point.lng)) {
console.log('bad position', data);
return;
}
var marker = new BMap.Marker(point, {
icon: markerIcon
});
mapInstance.addOverlay(marker);
var infowindow = new BMap.InfoWindow(generateTemplate(data, index), {
width: 200,
height: 100,
});
markers.push(marker);
infoWindows.push(infowindow);
results.push(data);
marker.addEventListener("click", function () {
closeAllInfowindows();
this.openInfoWindow(infowindow);
mapInstance.centerAndZoom(point, 15);
$('.infowindow-content').removeClass('active');
$('.infowindow-content').filter(function () {
return $(this).data('index') == index
}).addClass('active');
$('#dealers .results').scrollTop($('.results .infowindow-content[data-index="' + index + '"]').parent()[0].offsetTop - 220);
});
}
function addResult(data, index) {
var item = '<li>' + generateTemplate(data, index) + '</li>';
$('.results').append($(item));
}
function generateTemplate(data, index) {
if(typeof data == "undefined") {
return "no data";
}
var item = "<div class='infowindow-content' data-index='" + index + "'>";
item += '<h6 class="infowindow-title"> <span class="title">' + data.name + '</span> <span class="fa fa-chevron-down"></span></h6>';
// dealer category
if(data.category)
item += '<span class="infowindow-data">' + data.category + '</span>';
// distance
if(data.distance > 0) {
item += '<small>' + parseFloat(data.distance).toFixed(1) + data.distance_type + ' </small>';
// item += '<small>' + parseFloat(data.distance * 1.609).toFixed(1) + 'KM </small>';
}
// address
item += '<span class="infowindow-data"><br>' + data.address + '</span>';
// email
if(data.email)
item += '<span class="infowindow-data"><a href="mailto:' + data.email + '" target="_blank">' + data.email + '</a></span>';
// phone
if(data.phone)
item += '<span class="infowindow-data">' + data.phone + '</span>';
// links
item += '<span class="infowindow-data">';
item += '<a href="http://api.map.baidu.com/marker?location=' + data.lat + ',' + data.lng + '&output=html&s=gibberish" target="_blank">' + $_words['directions'] +
'</a> | <a href="#" data-zoom="' + index + '">' + $_words['zoom'] + '</a> ';
if(data.website) {
item += '| <a href="' + data.web + '" target="_blank">' + $_words['web'] + '</a>';
}
item += '</span>';
item += '</div>';
return item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment