一个infowindow googlemap标记内的多个优惠

时间:2016-02-22 12:36:35

标签: javascript ruby-on-rails google-maps

我试图帮助朋友改善他的应用。我现在尝试一周了:(在标记的同一信息窗口中添加多个信息(商品)。在同一地址/标记处有多个商品。不幸的是,信息窗口只显示一个商品点击一下就可以了!

我可以请求你的帮助吗?特别是作为编码的新人,我真的输了。提前谢谢。

这是algoliasearch.js.erb文件

function initAlgolia(
applicationId,
searchOnlyApiKey,
indexName,
offerPath,
newOfferBookingPath,
messagePath,
wishPath,
unwishPath,
assetPaths,
lat,
lng,
map,
markers,
currentUserWishedItemsIds,
admin,
i18nArray,
locale
) {
// Replace the following values by your ApplicationID and ApiKey.
var algolia = new AlgoliaSearch(
applicationId,
searchOnlyApiKey
);

var $hits = $('#hits');
var $pagination = $('#pagination');
var $stats = $('#stats');
var $q = $('#q');
var $hitTemplate = Hogan.compile($('#hit-template').text());
var $statsTemplate = Hogan.compile($('#stats-template').text());
var $paginationTemplate = Hogan.compile($('#pagination-template').text());
var $facets = $('#facets');
var $facetTemplate = Hogan.compile($('#facet-template').text());
var $sliderTemplate = Hogan.compile($('#slider-template').text());

var helper = new AlgoliaSearchHelper(algolia, indexName, {
// list of conjunctive facets (link to refine)
facets: [],
// list of disjunctive facets (checkbox to refine)
disjunctiveFacets: ['type_of_offer'],
// number of results per page
hitsPerPage: 80
});

var i18nCleanedArray = i18nArray.replace(/"/g, '"').replace(/'/g, "'");
var filter_by = JSON.parse(i18nCleanedArray)[0]
var on_rent = JSON.parse(i18nCleanedArray)[1]
var services = JSON.parse(i18nCleanedArray)[2]
var on_sale = JSON.parse(i18nCleanedArray)[3]
var show_offer = JSON.parse(i18nCleanedArray)[4]
var show_pic = JSON.parse(i18nCleanedArray)[5]
var hide_pic = JSON.parse(i18nCleanedArray)[6]
var unwish = JSON.parse(i18nCleanedArray)[7]
var wish = JSON.parse(i18nCleanedArray)[8]
var contact_owner = JSON.parse(i18nCleanedArray)[9]
var book = JSON.parse(i18nCleanedArray)[10]
var free = JSON.parse(i18nCleanedArray)[11]
var currency = JSON.parse(i18nCleanedArray)[12]
var daily_rate = JSON.parse(i18nCleanedArray)[13]
var weekly_rate = JSON.parse(i18nCleanedArray)[14]
var hourly_rate = JSON.parse(i18nCleanedArray)[15]

function sortByCountDesc(a, b) { return b.count - a.count; }
function sortByNumAsc(a, b) { return parseInt(a.label) - parseInt(b.label); }
var FACETS = [
{ name: 'type_of_offer', title: filter_by, sortFunction: sortByCountDesc, topListIfRefined: true },
];

var refinements = {};
var minReviewsCount = 0;

function bindInfoWindow(marker, map, infowindow, description) {
google.maps.event.addListener(marker, 'click', function() {
  infowindow.setContent(description);
  infowindow.open(map, marker);
});
}


function searchCallback(success, content) {
if (!success || content.query !== $q.val()) {
  // do not consider the result if there is an error
  // or if it is outdated -> query != $q.val()
  return;
}

var html = '';
var latLng;


if(markers) {
  for(var i = 0; i < markers.length; ++i) {
    if(markers[i]) {
      markers[i].setMap(null);
    }
  }
}

markers = [];
infowindows = [];

for (var i = 0; i < content.hits.length; i++) {
  latLng = new google.maps.LatLng(content.hits[i]._geoloc["lat"],content.hits[i]._geoloc["lng"]);
  if(locale == "en") {
    var infowindow = new google.maps.InfoWindow({
      content: content.hits[i].nature_en,
      maxWidth: '150'
    });
  } else {
    var infowindow = new google.maps.InfoWindow({
      content: content.hits[i].nature,
      maxWidth: '150'
    });
  }
  var marker = new google.maps.Marker({
    position: latLng,
    id: content.hits[i].id
  });
  marker.setMap(map);
  markers[i] = marker;
  infowindows[i] = infowindow;
  var offer_url = offerPath.replace(":id", content.hits[i].id);
  content.hits[i].offer_url = offer_url;
  var new_booking_url = newOfferBookingPath.replace(":offer_id", content.hits[i].id);
  content.hits[i].new_booking_url = new_booking_url;
  var message_url = messagePath.replace(":offer_id", content.hits[i].id);
  content.hits[i].message_url = message_url;
  var unwish_url = unwishPath.replace(":id", content.hits[i].id);
  content.hits[i].unwish_url = unwish_url;
  var wish_url = wishPath.replace(":id", content.hits[i].id);
  content.hits[i].wish_url = wish_url;
  var wished;
  var array = JSON.parse(currentUserWishedItemsIds);
  if(array.indexOf(content.hits[i].id) > -1) {
    wished = true;
    content.hits[i].wished = wished;
  } else {
    wished = false;
    content.hits[i].wished = wished;
  }
  assetPaths = assetPaths.replace(/&quot;/g, '"');
  var assetPathsArray = JSON.parse(assetPaths);
  var asset_path = assetPathsArray[0];
  if(content.hits[i].sell === null) {
    for(j in assetPathsArray) {
      if(assetPathsArray[j].indexOf(content.hits[i].nature) > -1) {
        asset_path = assetPathsArray[j];
      }
    }
  }
  content.hits[i].asset_path = asset_path;
  // I18n
  content.hits[i].show_offer = show_offer;
  content.hits[i].show_pic = show_pic;
  content.hits[i].hide_pic = hide_pic;
  content.hits[i].unwish = unwish;
  content.hits[i].wish = wish;
  content.hits[i].contact_owner = contact_owner;
  content.hits[i].book = book;
  content.hits[i].free = free;
  content.hits[i].currency = currency;
  content.hits[i].daily_rate = daily_rate;
  content.hits[i].weekly_rate = weekly_rate;
  content.hits[i].hourly_rate = hourly_rate;
  // end of I18n
  if(locale == "en") {
    var infowindowContent = "<div class='text-center'>"
      + "<img src='" + content.hits[i].asset_path +"' class='img-icon' width='50'>"
      + "<a href='" + content.hits[i].offer_url + "' class='nice-link info-link'>" + content.hits[i].nature_en + "</a>"
      + "</div>"
      + "<p>" + content.hits[i].description + "</p>"
  } else {
    var infowindowContent = "<div class='text-center'>"
      + "<img src='" + content.hits[i].asset_path +"' class='img-icon' width='50'>"
      + "<a href='" + content.hits[i].offer_url + "' class='nice-link info-link'>" + content.hits[i].nature + "</a>"
      + "</div>"
      + "<p>" + content.hits[i].description + "</p>"
  }
  bindInfoWindow(marker, map, infowindow, infowindowContent)
  html += $hitTemplate.render(content.hits[i]);
}
$hits.html(html);

if($('#hits').children().length == 0) {
  $('#hits').html(
    '<div class="padding-15" id="no-offer">' +
      '<div class="row">' +
        '<div class="col-xs-12">' +
          '<div class="img-nature-box">' +
            '<p>Pas de résultat</p>' +
            '<a href="offers/new">Je poste une annonce</a>' +
          '</div>' +
        '</div>' +
      '</div>' +
    '</div>'
  )
}

$('.offer-stream-box .neutralize').on('click', function(e) {
  showOrHidePicture($(this));
});

$('.offer-stream-box').on('click', function(e) {
  showOrHidePicture($(this));
});

$('.offer-stream-box').on('mouseenter', function(e) {
  var id = $(this).attr('id').slice(6, $(this).attr('id').length)
  var markerToAnimate = $.grep(markers, function(e) { return e.id == id })
  markerToAnimate[0].setAnimation(google.maps.Animation.BOUNCE);
});

$('.offer-stream-box').on('mouseleave', function(e) {
  var id = $(this).attr('id').slice(6, $(this).attr('id').length)
  var markerToAnimate = $.grep(markers, function(e) { return e.id == id })
  markerToAnimate[0].setAnimation(null);
});

togglePaddingRight();
adjustNatureIconsSize();
$(".fancybox").fancybox();

// facets: display the conjunctive+disjunctive facets
html = '';
var facetResult = null;
var facetConfig = null;
var isDisjunctive = null;

for (var j=0; j<FACETS.length; ++j) {
  facetConfig = FACETS[j];
  facetResult = content['disjunctiveFacets'][facetConfig.name] || null;
  isDisjunctive = (content['disjunctiveFacets'][facetConfig.name]) ? true : false;

  if (facetResult) {

    if (facetConfig.name === 'customerReviewCount') {
      // add a slider fetching the 'max' value of 'customerReviewCount' from `content.facets_stats.customerReviewCount`
      html += $sliderTemplate.render({ facet: facetConfig.name, title: facetConfig.title, max: content.facets_stats.customerReviewCount.max, current: minReviewsCount });
    } else {
      // other facets

      // collect all values from `facetResult` to sort them by facetConfig.sortFunction
      var values = [];
      for (var v in facetResult) {
        if(v === "rent") {
          values.push({
            label: on_rent,
            value: v,
            count: facetResult[v],
            refined: helper.isRefined(facetConfig.name, v)
          });
        }
        if(v === "service") {
          values.push({
            label: services,
            value: v,
            count: facetResult[v],
            refined: helper.isRefined(facetConfig.name, v)
          });
        }
        if(v === "sell") {
          values.push({
            label: on_sale,
            value: v,
            count: facetResult[v],
            refined: helper.isRefined(facetConfig.name, v)
          });
        }
      }

      // render the facet
      html += $facetTemplate.render({
        facet: facetConfig.name,
        title: facetConfig.title,
        values: values.slice(0, 10),
        has_other_values: values.length > 10,
        other_values: values.slice(10),
        disjunctive: isDisjunctive
      });
    }

  }
}
$facets.html(html);
toggleFacets();

// render pagination
var pages = [];
if (content.page > 5) {
  pages.push({ current: false, number: 1 });
  pages.push({ current: false, number: '...', disabled: true });
}
for (var p = content.page - 5; p < content.page + 5; ++p) {
  if (p < 0 || p >= content.nbPages) {
    continue;
  }
  pages.push({ current: content.page == p, number: (p + 1) });
}
if (content.page + 5 < content.nbPages) {
  pages.push({ current: false, number: '...', disabled: true });
  pages.push({ current: false, number: content.nbPages });
}
$pagination.html($paginationTemplate.render({ pages: pages, prev_page: (content.page > 0 ? content.page : false), next_page: (content.page + 1 < content.nbPages ? content.page + 2 : false) }));

adjustDivsHeights();
$('#sidebar').click();


// update URL anchor
var refinements = [];
for (var refine in helper.refinements) {
  if (helper.refinements[refine]) {
    var i = refine.indexOf(':');
    var r = {};
    r[refine.slice(0, i)] = refine.slice(i + 1);
    refinements.push(r);
  }
}
for (var refine in helper.disjunctiveRefinements) {
  for (var value in helper.disjunctiveRefinements[refine]) {
    if (helper.disjunctiveRefinements[refine][value]) {
      var r = {};
      r[refine] = value;
      refinements.push(r);
    }
  }
}
location.replace('#q=' + encodeURIComponent(content.query) + '&page=' + content.page + '&minReviewsCount=' + minReviewsCount + '&refinements=' + encodeURIComponent(JSON.stringify(refinements)));

// scroll on top
window.scrollTo(0, 0);
}

// perform a search
function search() {

var params = {
  // retrieve maximum 50 values per facet to display the "more" link
  maxValuesPerFacet: 50
};
// plug review_count slider refinement
if (minReviewsCount > 0) {
  params.numericFilters = 'customerReviewCount>=' + minReviewsCount;
}
// if we're sorting by something,
// make the typo-tolerance more strict
if (helper.index != indexName) {
  // disable if not the "default" index (sort by price, etc...)
  params.typoTolerance = false;
 }

var radius

if(admin == 'true') {
  radius = 100000
} else {
  radius = 2090
}

// perform the query
helper.search($q.val(), searchCallback, {
  aroundLatLng: lat + ',' + lng,
  aroundRadius: radius // 1km around unless admin
});
}

// init: fetch anchor params and init the associated variables
if (location.hash && location.hash.indexOf('#q=') === 0) {
var params = location.hash.substring(3);
var pageParamOffset = params.indexOf('&page=');
var minReviewsCountParamOffset = params.indexOf('&minReviewsCount=');
var refinementsParamOffset = params.indexOf('&refinements=');

var q = decodeURIComponent(params.substring(0, pageParamOffset));
var page = parseInt(params.substring(pageParamOffset + 6, minReviewsCountParamOffset));
minReviewsCount = parseInt(params.substring(minReviewsCountParamOffset + 17, refinementsParamOffset));
var refinements = JSON.parse(decodeURIComponent(params.substring(refinementsParamOffset + 13)));

$q.val(q);
for (var i = 0; i < refinements.length; ++i) {
  for (var refine in refinements[i]) {
    helper.toggleRefine(refine, refinements[i][refine]);
  }
}
helper.setPage(page);
}


// input binding
var lastQuery = $q.val();
$q.on('keyup change', function() {
if ($q.val() != lastQuery) {
  lastQuery = $q.val();
  // performing a new full-text query reset the pagination and the refinements
  minReviewsCount = 0;
  helper.setPage(0);
  helper.clearRefinements();
  search();
}
}).focus();

// load results
search();

// click binding
window.showMoreLess = function(link) {
$(link).closest('ul').find('.show-more').toggle();
};
window.toggleRefine = function(facet, value) {
// refinining a facet reset the pagination
helper.setPage(0);
helper.toggleRefine(facet, value);
};
window.gotoPage = function(page) {
helper.gotoPage(+page - 1);
};

window.sortBy = function(index_suffic, link) {
$(link).closest('.btn-group').find('.sort-by').text($(link).text());
// set target index name
helper.index = indexName + index_suffic;
// reset page
helper.setPage(0);
// perform the query
search();
};

}

1 个答案:

答案 0 :(得分:0)

您将许多标记放在同一位置,因此只有顶部的标记才能显示以接收点击并弹出其信息窗口。您需要汇总数据,以便可以访问给定位置的所有商品。您可以为每个商品创建一个单独的信息窗口(但是您需要将它们分隔开以便可以看到它们),或者您可以将所有商品组合到一个信息窗口中。