JQuery: collection array length being capped at 100 - javascript

I'm using Splunk Web Framework and Google Maps app to create a custom map implementation. The problem i'm seeing is when I send splunk search results information into the google maps js it caps my rows at 100. Can someone take a look at the code below and see if there any anywhere that might cause an array to be capped at 100?
/** #license
* RequireJS plugin for async dependency load like JSONP and Google Maps
* Author: Miller Medeiros
* Version: 0.1.1 (2011/11/17)
* Released under the MIT license
*/
define('async',[],function(){
var DEFAULT_PARAM_NAME = 'callback',
_uid = 0;
function injectScript(src){
var s, t;
s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src;
t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s,t);
}
function formatUrl(name, id){
var paramRegex = /!(.+)/,
url = name.replace(paramRegex, ''),
param = (paramRegex.test(name))? name.replace(/.+!/, '') : DEFAULT_PARAM_NAME;
url += (url.indexOf('?') < 0)? '?' : '&';
return url + param +'='+ id;
}
function uid() {
_uid += 1;
return '__async_req_'+ _uid +'__';
}
return{
load : function(name, req, onLoad, config){
if(config.isBuild){
onLoad(null); //avoid errors on the optimizer
}else{
var id = uid();
window[id] = onLoad; //create a global variable that stores onLoad so callback function can define new module after async load
injectScript(formatUrl(name, id));
}
}
};
});
requirejs.s.contexts._.nextTick = function(f){f()}; require(['css'], function(css) { css.addBuffer('splunkjs/css/googlemap.css'); }); requirejs.s.contexts._.nextTick = requirejs.nextTick;
define('splunkjs/mvc/googlemapview',['require','exports','module','underscore','./mvc','./basesplunkview','./messages','async!http://maps.googleapis.com/maps/api/js?sensor=false','css!../css/googlemap.css'],function(require, exports, module) {
var _ = require('underscore');
var mvc = require('./mvc');
var BaseSplunkView = require("./basesplunkview");
var Messages = require("./messages");
require("async!http://maps.googleapis.com/maps/api/js?sensor=false");
require("css!../css/googlemap.css");
var GoogleMapView = BaseSplunkView.extend({
moduleId: module.id,
className: "splunk-googlemap",
options: {
managerid: null,
data: "preview"
},
initialize: function() {
this.configure();
this.bindToComponentSetting('managerid', this._onManagerChange, this);
this.map = null;
this.markers = [];
// If we don't have a manager by this point, then we're going to
// kick the manager change machinery so that it does whatever is
// necessary when no manager is present.
if (!this.manager) {
this._onManagerChange(mvc.Components, null);
}
},
_onManagerChange: function(managers, manager) {
if (this.manager) {
this.manager.off(null, null, this);
this.manager = nul=]=]l;
}
=]== if (this.resultsModel) {
= this.resultsModel.off(null, null, this);
this.resultsModel.destroy();
this.resultsModel = null;
}
if (!manager) {
this.message('no-search');
return;
}
// Clear any messages, since we have a new manager.
this.message("empty");
this.manager = manager;
this.resultsModel = manager.data(this.settings.get("data"), {
output_mode: "json_rows"
});
manager.on("search:start", this._onSearchStart, this);
manager.on("search:progress", this._onSearchProgress, this);
manager.on("search:cancelled", this._onSearchCancelled, this);
manager.on("search:error", this._onSearchError, this);
this.resultsModel.on("data", this.render, this);
this.resultsModel.on("error", this._onSearchError, this);
manager.replayLastSearchEvent(this);
},
_onSearchCancelled: function() {
this._isJobDone = false;
this.message('cancelled');
},
_onSearchError: function(message, err) {
this._isJobDone = false;
var msg = message;
if (err && err.data && err.data.messages && err.data.messages.length) {
msg = _(err.data.messages).pluck('text').join('; ');
}
this.message({
level: "error",
icon: "warning-sign",
message: msg
});
},
_onSearchProgress: function(properties) {
properties = properties || {};
var content = properties.content || {};
var previewCount = content.resultPreviewCount || 0;
var isJobDone = this._isJobDone = content.isDone || false;
if (previewCount === 0 && isJobDone) {
this.message('no-results');
return;
}
if (previewCount === 0) {
this.message('waiting');
return;
}
},
_onSearchStart: function() {
this._isJobDone = false;
this.message('waiting');
},
clearMarkers: function() {
var count = this.markers.length;
for (var i = 0; i < count; ++i)
this.markers[i].setMap(null);
this.markers.length = 0;
},
createMap: function() {
this.map = new google.maps.Map(this.el, {
center: new google.maps.LatLng(47.60, -122.32),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
this.map.setOptions(this.options);
},
message: function(info) {
this.map = null;
Messages.render(info, this.$el);
},
render: function() {
if (!this.manager) {
return;
}
if (!this.resultsModel || !this.resultsModel.hasData()) {
if (this.resultsModel && !this.resultsModel.hasData() && this._isJobDone) {
this.message("no-results");
}
return this;
}
if (!this.map) {
this.createMap();
}
var that = this;
this.clearMarkers();
this.resultsModel.collection().each(function(row) {
var lat = parseFloat(row.get("lat"));
var lng = parseFloat(row.get("lng"));
var latlng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: latlng,
map: that.map
});
that.markers.push(marker);
});
return this;
}
});
return GoogleMapView;
});
requirejs.s.contexts._.nextTick = function(f){f()}; require(['css'], function(css) { css.setBuffer('/* */\n\n/* Bootstrap Css Map Fix*/\n.splunk-googlemap img { \n max-width: none;\n}\n/* Bootstrap Css Map Fix*/\n.splunk-googlemap label { \n width: auto; \n display:inline; \n} \n/* Set a small height on the map so that it shows up*/\n.splunk-googlemap {\n min-height: 100px;\n height: 100%;\n}\n'); }); requirejs.s.contexts._.nextTick = requirejs.nextTick;

From a quick search it seems it could be splunk capping at 100?
See http://answers.splunk.com/answers/52782/100-result-limit-in-js-sdk.html

Related

Javascript: What is this? Array in array? I don't understand why I can't access it? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 2 years ago.
Good morning,
I get data from JSON, with physical addresses that get converted to geo coordinates (If needed I can put the whole code here or a link to the site under construction).
Then I need to work with these coordinates to calculate distances or whatever.
But somehow I can't access them.
my code (extract) looks like this:
var positionsCenter = [];
for (let i = 0; i < positions.length; i++) {
lux.geocode({
num: positions[i].num,
street: positions[i].street,
zip: positions[i].zip,
locality: positions[i].locality
}, function (position) {
**positionsCenter[i] = position;**
var pFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform(position, 'EPSG:2169', 'EPSG:3857')),
id: i
});
vectorSource.addFeature(pFeature);
});
}
These are coordinates on a map (vector layer) but something's wrong.
When I output this via:
console.log(positionsCenter);
It gives me this:
[]
0: (2) [75980.11870000046, 75098.00039954418]
1: (2) [87897.10419999996, 63546.633999540085]
2: (2) [88238.34310000022, 63389.17289954127]
3: (2) [73701.38559999966, 76385.07059954498]
4: (2) [71212.77219999957, 74969.26619954518]
5: (2) [80450.28039999957, 72414.96529954427]
6: (2) [83811.06230000037, 75487.27249954658]
7: (2) [86081.38100000011, 86362.58049954918]
8: (2) [77022.02340000033, 80667.17809954635]
9: (2) [66163.39429999988, 62664.86699954068]
length: 10
__proto__: Array(0)
But when I try to access one of the entries like this:
console.log(positionsCenter[1]);
or
console.log(positionsCenter[1][1]);
or even
console.log(positionsCenter.length);
it's always undefined!
What do I miss? I'm confused :-/
Thank you for any help.
Best regards,
Claude
Here's the whole part of this code:
var map;
var vectorSource;
var highlightedFeature = null;
var selectedFeature = null;
function loadMap() {
map = new lux.Map({
target: 'map',
bgLayer: 'basemap_2015_global', //default basemap_2015_global, streets_jpeg
zoom: 16, //18
position: [75977, 75099],
showLayerInfoPopup: true,
search: {
target: 'searchbox',
dataSets: ['Adresse', 'Coordinates']
}
});
//-------------------------------------------------------------- FEATURES -
vectorSource = new ol.source.Vector({
features: []
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
function styleFunction(feature, resolution) {
var sti = feature.get('status');
const liv = 'livraison';
const tak = 'take-away';
var newColor = [128, 128, 128];
if (sti.includes('ouvert')) {
newColor = [0, 255, 0];
}
var imgSource = '../images/pin.png';
if (sti.includes(liv) && sti.includes(tak)) {
imgSource = '../images/pin-livraison-takeaway.png';
} else {
if (sti.includes(liv)) {
imgSource = '../images/pin-livraison.png';
} else {
if (sti.includes(tak)) {
imgSource = '../images/pin-takeaway.png';
}
}
}
var isSelected = feature.get('selected') || feature.get('highlighted');
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 0.5],
color: newColor,
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
src: imgSource,
scale: isSelected ? 1.5 : 1
}))
});
return [iconStyle];
}
vectorLayer.setStyle(styleFunction);
map.addLayer(vectorLayer);
for (let i = 0; i < positions.length; i++) {
lux.geocode({
num: positions[i].num,
street: positions[i].street,
zip: positions[i].zip,
locality: positions[i].locality
}, function (position) {
positionsCenter[i] = position;
var pFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform(position, 'EPSG:2169', 'EPSG:3857')),
id: i
});
const sti = statuses[i];
pFeature.set('status', sti);
pFeature.setId(i);
pFeature.set('selected', false);
pFeature.set('highlighted', false);
vectorSource.addFeature(pFeature);
});
//console.log(positions[i]);
}
map.on('click', function (evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature !== undefined) {
if (selectedFeature !== null) {
selectedFeature.set('selected', false);
selectedFeature = null;
}
feature.set('selected', true);
selectedFeature = feature;
var outPut = feature.get('id');
infoField.innerHTML = arr[outPut].innerHTML;
infoField.style.display = 'block';
CloseinfoField.style.display = 'block';
galImage.style.display = 'none';
ClosegalImage.style.display = 'none';
getThumbs(outPut);
for (let j = 0; j < arr.length; j++) {
arr[j].classList.remove('active');
}
arr[outPut].className += ' active';
var current = document.getElementById('item' + outPut);
current.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
} else {
console.log('');
}
});
map.on('pointermove', function (evt) {
if (highlightedFeature !== null) {
highlightedFeature.set('highlighted', false);
highlightedFeature = null;
}
var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature !== undefined) {
highlightedFeature = feature;
highlightedFeature.set('highlighted', true);
}
});
//------------------------------------------------------------------ DISTANCE -
var sourceProj = map.getView().getProjection();
var wgs84Sphere = new ol.Sphere(6378137);
var coordinates1 = [75977, 75099];
var coordinates2 = [76977, 75099];
// EDIT/UPDATE ----------------------------------------
function delay(ms) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, ms);
});
}
function getFive() {
return delay(100).then(function () {
return positionsCenter[0];
})
}
getFive().then(function (five) {
console.log(five);
});
// EDIT ----------------------------------------
var c1 = ol.proj.transform(coordinates1, sourceProj, 'EPSG:4326');
var c2 = ol.proj.transform(coordinates2, sourceProj, 'EPSG:4326');
var distance = wgs84Sphere.haversineDistance(c1, c2);
console.log(distance);
//----------------------------------------------------------------- /DISTANCE -
document.getElementById('myLocation').addEventListener('click', getLocation);
document.getElementById('navList').addEventListener('click', getnavList);
}

Problem getting my correct location with google chrome Javascript

I have the following code which is responsible for the geographical location of latitude, longitude and the map of where one is:
<html>
<head>
<title>javascript-mobile-desktop-geolocation With No Simulation with Google Maps</title>
<meta name = "viewport" content = "width = device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
<style>
body {font-family: Helvetica;font-size:11pt;padding:0px;margin:0px}
#title {background-color:#e22640;padding:5px;}
#current {font-size:10pt;padding:5px;}
</style>
</head>
<body onload="initialiseMap();initialise()">
<h1>location GPS</h1>
<div id="current">Initializing...</div>
<div id="map_canvas" style="width:320px; height:350px"></div>
<script src="js/geoPosition.js" type="text/javascript" charset="utf-8">
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function initialiseMap()
{
var myOptions = {
zoom: 4,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function initialise()
{
if(geoPosition.init())
{
document.getElementById('current').innerHTML="Receiving...";
geoPosition.getCurrentPosition(showPosition,function(){document.getElementById('current').innerHTML="Couldn't get location"},{enableHighAccuracy:true});
}
else
{
document.getElementById('current').innerHTML="Functionality not available";
}
}
function showPosition(p)
{
var latitude = parseFloat( p.coords.latitude );
var longitude = parseFloat( p.coords.longitude );
document.getElementById('current').innerHTML="latitude=" + latitude + " longitude=" + longitude;
var pos=new google.maps.LatLng( latitude , longitude);
map.setCenter(pos);
map.setZoom(14);
var infowindow = new google.maps.InfoWindow({
content: "<strong>yes</strong>"
});
var marker = new google.maps.Marker({
position: pos,
map: map,
title:"You are here"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
</script>
</body>
</html>
the file geoPosition.js:
var bb = {
success: 0,
error: 0,
blackberryTimeoutId : -1
};
function handleBlackBerryLocationTimeout()
{
if(bb.blackberryTimeoutId!=-1) {
bb.error({ message: "Timeout error",
code: 3
});
}
}
function handleBlackBerryLocation()
{
clearTimeout(bb.blackberryTimeoutId);
bb.blackberryTimeoutId=-1;
if (bb.success && bb.error) {
if(blackberry.location.latitude==0 && blackberry.location.longitude==0) {
//http://dev.w3.org/geo/api/spec-source.html#position_unavailable_error
//POSITION_UNAVAILABLE (numeric value 2)
bb.error({message:"Position unavailable", code:2});
}
else
{
var timestamp=null;
//only available with 4.6 and later
//http://na.blackberry.com/eng/deliverables/8861/blackberry_location_568404_11.jsp
if (blackberry.location.timestamp)
{
timestamp = new Date( blackberry.location.timestamp );
}
bb.success( { timestamp: timestamp ,
coords: {
latitude: blackberry.location.latitude,
longitude: blackberry.location.longitude
}
});
}
//since blackberry.location.removeLocationUpdate();
//is not working as described http://na.blackberry.com/eng/deliverables/8861/blackberry_location_removeLocationUpdate_568409_11.jsp
//the callback are set to null to indicate that the job is done
bb.success = null;
bb.error = null;
}
}
var geoPosition=function() {
var pub = {};
var provider=null;
var u="undefined";
var ipGeolocationSrv = 'http://freegeoip.net/json/?callback=JSONPCallback';
pub.getCurrentPosition = function(success,error,opts)
{
provider.getCurrentPosition(success, error,opts);
}
pub.jsonp = {
callbackCounter: 0,
fetch: function(url, callback) {
var fn = 'JSONPCallback_' + this.callbackCounter++;
window[fn] = this.evalJSONP(callback);
url = url.replace('=JSONPCallback', '=' + fn);
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = url;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
},
evalJSONP: function(callback) {
return function(data) {
callback(data);
}
}
};
pub.confirmation = function()
{
return confirm('This Webpage wants to track your physical location.\nDo you allow it?');
};
pub.init = function()
{
try
{
var hasGeolocation = typeof(navigator.geolocation)!=u;
if( !hasGeolocation ){
if( !pub.confirmation() ){
return false;
}
}
if ( ( typeof(geoPositionSimulator)!=u ) && (geoPositionSimulator.length > 0 ) ){
provider=geoPositionSimulator;
} else if (typeof(bondi)!=u && typeof(bondi.geolocation)!=u ) {
provider=bondi.geolocation;
} else if ( hasGeolocation ) {
provider=navigator.geolocation;
pub.getCurrentPosition = function(success, error, opts)
{
function _success(p) {
//for mozilla geode,it returns the coordinates slightly differently
var params;
if(typeof(p.latitude)!=u) {
params = {
timestamp: p.timestamp,
coords: {
latitude: p.latitude,
longitude: p.longitude
}
};
} else {
params = p;
}
success( params );
}
provider.getCurrentPosition(_success,error,opts);
}
} else if(typeof(window.blackberry)!=u && blackberry.location.GPSSupported) {
// set to autonomous mode
if(typeof(blackberry.location.setAidMode)==u) {
return false;
}
blackberry.location.setAidMode(2);
//override default method implementation
pub.getCurrentPosition = function(success,error,opts)
{
//passing over callbacks as parameter didn't work consistently
//in the onLocationUpdate method, thats why they have to be set outside
bb.success = success;
bb.error = error;
//function needs to be a string according to
//http://www.tonybunce.com/2008/05/08/Blackberry-Browser-Amp-GPS.aspx
if(opts['timeout']) {
bb.blackberryTimeoutId = setTimeout("handleBlackBerryLocationTimeout()",opts['timeout']);
} else {
//default timeout when none is given to prevent a hanging script
bb.blackberryTimeoutId = setTimeout("handleBlackBerryLocationTimeout()",60000);
}
blackberry.location.onLocationUpdate("handleBlackBerryLocation()");
blackberry.location.refreshLocation();
}
provider = blackberry.location;
} else if ( typeof(Mojo) !=u && typeof(Mojo.Service.Request)!="Mojo.Service.Request") {
provider = true;
pub.getCurrentPosition = function(success, error, opts)
{
parameters = {};
if( opts ) {
//http://developer.palm.com/index.php?option=com_content&view=article&id=1673#GPS-getCurrentPosition
if (opts.enableHighAccuracy && opts.enableHighAccuracy == true ){
parameters.accuracy = 1;
}
if ( opts.maximumAge ) {
parameters.maximumAge = opts.maximumAge;
}
if (opts.responseTime) {
if( opts.responseTime < 5 ) {
parameters.responseTime = 1;
} else if ( opts.responseTime < 20 ) {
parameters.responseTime = 2;
} else {
parameters.timeout = 3;
}
}
}
r = new Mojo.Service.Request( 'palm://com.palm.location' , {
method:"getCurrentPosition",
parameters:parameters,
onSuccess: function( p ){
success( { timestamp: p.timestamp,
coords: {
latitude: p.latitude,
longitude: p.longitude,
heading: p.heading
}
});
},
onFailure: function( e ){
if (e.errorCode==1) {
error({ code: 3,
message: "Timeout"
});
} else if (e.errorCode==2){
error({ code: 2,
message: "Position unavailable"
});
} else {
error({ code: 0,
message: "Unknown Error: webOS-code" + errorCode
});
}
}
});
}
}
else if (typeof(device)!=u && typeof(device.getServiceObject)!=u) {
provider=device.getServiceObject("Service.Location", "ILocation");
//override default method implementation
pub.getCurrentPosition = function(success, error, opts){
function callback(transId, eventCode, result) {
if (eventCode == 4) {
error({message:"Position unavailable", code:2});
} else {
//no timestamp of location given?
success( { timestamp:null,
coords: {
latitude: result.ReturnValue.Latitude,
longitude: result.ReturnValue.Longitude,
altitude: result.ReturnValue.Altitude,
heading: result.ReturnValue.Heading }
});
}
}
//location criteria
var criteria = new Object();
criteria.LocationInformationClass = "BasicLocationInformation";
//make the call
provider.ILocation.GetLocation(criteria,callback);
}
} else {
pub.getCurrentPosition = function(success, error, opts) {
pub.jsonp.fetch(ipGeolocationSrv,
function( p ){ success( { timestamp: p.timestamp,
coords: {
latitude: p.latitude,
longitude: p.longitude,
heading: p.heading
}
});});
}
provider = true;
}
}
catch (e){
if( typeof(console) != u ) console.log(e);
return false;
}
return provider!=null;
}
return pub;
}();
In Internet explorer works correctly for me, but when I try it on Google Chrome it shows me the location of another city near my region. I'd like to be able to solve it, and let me show my correct location in google chrome.
I noticed that in internet explorer it takes a few seconds more to load to visualize the location, perhaps in the google chrome lacks some pre-load cleaning or some compatibility.
In Internet Explorer it is right:
but in google chrome the location shows me wrong:
My objective is to be able to obtain my location with the map in an exact way in different browsers with javascript or some type code on the client side.
If anyone knows, of course, I appreciate your attention.

Videojs removeChild method not working

I'm writing a new plugin for videojs. I have an issue with the if statement:
if (getCTime == 5 && c == true) {
this.removeChild(createDiv);
}
It can not remove div element after 5 seconds. What should I do?
Code:
(function() {
'use strict';
//Create Component
videojs.containerDiv = videojs.Component.extend({
init: function(player, options) {
videojs.Component.call(this, player, options);
}
});
// get current time and create new element
videojs.containerDiv.prototype.timeUpdate = function(player, options) {
var c = false;
this.player_.on('timeupdate', function() {
var getCTime = Math.floor(this.cache_.currentTime);
var createDiv = new videojs.containerDiv(this, options);
// In 2 seconds are show ads
if (getCTime == 2 && c == false) {
// Create new div for ads
this.addChild(createDiv);
//Close ads
this.one(createDiv.newDivClose_,'click', function() {
this.removeChild(createDiv);
});
c = true;
}
if (getCTime == 5 && c == true) {
this.removeChild(createDiv);
}
});
}
videojs.containerDiv.prototype.createEl = function() {
var newDiv = videojs.createEl('div', {
className: 'vjs-new-div'
});
var newDivInside = videojs.createEl('div', {
className: 'vjs-new-div-inside'
});
var newDivClose = videojs.createEl('div', {
className: 'vjs-btn-close',
innerHTML: 'x'
});
this.newDivClose_ = newDivClose;
newDiv.appendChild(this.newDivClose_);
this.contentEl_ = newDivInside;
this.contentEl_.innerHTML = this.innerHTML();
newDiv.appendChild(this.contentEl_);
return newDiv;
};
videojs.containerDiv.prototype.innerHTML = function() {
this.textAds = "Hello World";
return this.textAds;
}
var pluginFn = function(options) {
var myComponent = new videojs.containerDiv(this, options);
myComponent.timeUpdate(this, options);
};
videojs.plugin( 'myPlugin', pluginFn );
})();

Icon of marker does not change the second time on google maps

I am building a web application to search for events using the backbone. In the home page, I have 10 images (that corresponds to the events) on right column and each of them have an id of event. In the left column have the markers that corresponds to the location of the images and each of the markers have an id of event too.
I have a function that detects an event mouseover of the image, and when this event occurs the icon of the marker that corresponds to the image is changed. And when I do a mouseover of another image the icon before is changed again to the icon default.
But my problem is when I do the mouseover the same image twice, the icon of the marker is not changed. Here's a gif to better understand the issue:
the problem
My code:
ev.views.Home = Backbone.View.extend({
initialize: function(map, p, firstEntry){
var that = this;
that.template = _.template(ev.templateLoader.get('home'));
ev.router.on("route", function(route, params) {
that.deleteMarkers();
});
that.map = map;
that.firstEntry = firstEntry;
that.p = p; // valor da pagina
that.icons = [];
that.render(that.map, that.p, that.firstEntry);
},
local: function(map){
...
},
deleteMarkers: function(){
...
},
events: {
'click #search' : 'searchKey',
'click #maisFiltros' : 'maisFiltros',
'mouseover .back' : 'overImagem'
},
overImagem: function(ev){
var target = $(ev.currentTarget);
var id = $(target).data("id");
this.icons.push(id);
var last = this.icons.length-2;
if(typeof this.icons[last] !== 'undefined'){
if(this.icons[last] !== this.icons[last+1]){
for (var i = 0; i < this.marcadores.markers.length; i++) {
if(id == this.marcadores.markers[i].get('id')){
this.marcadores.markers[i].setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
}
}
if(this.icons.length !== 1){
this.marcadores.markers[last].setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
}
}
}else{
for (var i = 0; i < this.marcadores.markers.length; i++) {
if(id == this.marcadores.markers[i].get('id')){
this.marcadores.markers[i].setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
}
}
}
},
searchKey: function(){
...
},
render: function(map, p, firstEntry){
var that = this;
that.map = map;
that.firstEntry = firstEntry;
that.p = p;
that.$el.html(that.template());
setTimeout(function() {
that.local(that.map);
if(that.firstEntry != 0){
that.marcadores = new ev.views.Markers(that.map,p);
$("#lista").html(new ev.views.ListaEventos(that.p).el);
}else{
that.keyword = ev.keyword.get('key');
that.secondSearch = new ev.views.Pesquisa(that.keyword, that.p, that.map);
$("#lista").html(that.secondSearch.el);
}
}, 0);
return that;
}
});
View of markers:
ev.views.Markers = Backbone.View.extend({
initialize: function(map,p){
this.map = map;
this.p = p;
this.render(this.map,this.p);
},
apagar: function(){
for (var i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
this.markers = [];
},
render: function(map,p){
var that = this;
that.markers = [];
var imagens = new ev.models.ImagemCollection();
imagens.fetch({
success: function(){
var len = imagens.models.length;
var startPos = (that.p - 1) * 10;
var endPos = Math.min(startPos + 10 , len);
var marcadores = imagens.models;
for (var i = startPos; i < endPos; i++) {
var myLatlng = new google.maps.LatLng(marcadores[i].get('latitude'),marcadores[i].get('longitude'));
var marker = new google.maps.Marker({
position: myLatlng,
map: that.map,
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png',
id: marcadores[i].get('id')
});
that.markers.push(marker);
}
return that;
}
});
}
});
what I'm doing wrong.

How to set the zoom level for a single location on a bing map

I have the following js object:
virtualEarthBingMap = {
map : "",
propertiesDataArray : [],
locations : [],
initialLatLong : "",
initialZoom : "",
isInitialized : false,
MM : "",
overMap : false,
init : function(){
},
addLoadEvent : function(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
},
pushpinObj : function(){
this.number;
this.lat;
this.longitude;
this.type;
this.iconstyle;
},
generatePushpinData : function(rowCount){
if(rowCount == undefined){
rowCount = "";
}
//initiate hidden field objects
var pushPinNumberObj = document.getElementsByName("pushpin-number"+rowCount);
var pushPinLatObj = document.getElementsByName("pushpin-lat"+rowCount);
var pushPinLongObj = document.getElementsByName("pushpin-long"+rowCount);
var pushPinTypeObj = document.getElementsByName("pushpin-type"+rowCount);
var pushPinIconStyleObj = document.getElementsByName("pushpin-iconstyle"+rowCount);
for(i=0; i < pushPinNumberObj.length; i++){
var propertyData = new virtualEarthBingMap.pushpinObj;
propertyData.number = Number(pushPinNumberObj[i].value);
propertyData.lat = pushPinLatObj[i].value;
propertyData.longitude = pushPinLongObj[i].value;
propertyData.type = pushPinTypeObj[i].value;
if(pushPinIconStyleObj!= null && pushPinIconStyleObj.length>0){
propertyData.iconstyle = pushPinIconStyleObj[i].value;
}
virtualEarthBingMap.propertiesDataArray.push(propertyData);
}
},
mouseEvent: function (e){
if(e.eventName == 'mouseout')
virtualEarthBingMap.overMap = false;
else if(e.eventName == 'mouseover')
virtualEarthBingMap.overMap = true;
},
//renders VEMap to myMap div
getMap: function (mapObj, rowCount) {
if(rowCount == undefined){
rowCount = "";
}
try{
virtualEarthBingMap.MM = Microsoft.Maps;
//Set the map options
var mapOptions = { credentials:document.getElementById("bingKey"+rowCount).value,
mapTypeId: virtualEarthBingMap.MM.MapTypeId.road,
enableClickableLogo: false,
enableSearchLogo: false,
tileBuffer: Number(document.getElementById("tileBuffer"+rowCount).value)};
virtualEarthBingMap.map = new virtualEarthBingMap.MM.Map(document.getElementById("map"+rowCount), mapOptions);
var dataLayer = new virtualEarthBingMap.MM.EntityCollection();
virtualEarthBingMap.map.entities.push(dataLayer);
var pushpinOptions,pushpin,propertyData;
for(var x=0; x < virtualEarthBingMap.propertiesDataArray.length; x++){
propertyData = virtualEarthBingMap.propertiesDataArray[x];
if(document.getElementsByName(("pushpin-iconstyle"+rowCount)).length > 0)//All other maps push pins
{
pushpinOptions ={icon: mapObj.getCustomIcon(propertyData.iconstyle)};
}
else//classic search map push pin
{
pushpinOptions ={icon: mapObj.getCustomIcon(propertyData.type)};
}
// creating a pushpin for every property
pushpin = new virtualEarthBingMap.MM.Pushpin(new virtualEarthBingMap.MM.Location(Number(propertyData.lat), Number(propertyData.longitude)), pushpinOptions);
pushpin.setOptions({typeName:("pushpin"+rowCount)});
// set pushpin on map
dataLayer.push(pushpin);
// adding to locations array to be used for setMapView when there are more than one property on a map
virtualEarthBingMap.locations.push(new virtualEarthBingMap.MM.Location(Number(propertyData.lat), Number(propertyData.longitude)));
};
//Handle blur event for map
if(rowCount == ""){
$("html").click(function() {
if(!virtualEarthBingMap.overMap)
virtualEarthBingMap.map.blur();
});
}
//Set the events for map, pushpin and infobox
virtualEarthBingMap.map.blur();//Removes focus from the map control
virtualEarthBingMap.MM.Events.addHandler(pushpin, 'mouseover', function (e) { virtualEarthBingMap.displayInfobox(e, rowCount)});
virtualEarthBingMap.MM.Events.addHandler(pushpin, 'click', function (e) { virtualEarthBingMap.displayInfobox(e, rowCount)});
virtualEarthBingMap.MM.Events.addHandler(virtualEarthBingMap.map, 'viewchangeend', virtualEarthBingMap.hideInfobox);
virtualEarthBingMap.MM.Events.addHandler(virtualEarthBingMap.map, 'mouseout', virtualEarthBingMap.mouseEvent);
virtualEarthBingMap.MM.Events.addHandler(virtualEarthBingMap.map, 'mouseover', virtualEarthBingMap.mouseEvent);
//Plot the pushpin
mapObj.setMapView();
}catch(e){
mapObj.displayMapError(rowCount);
}
//clean up properties data array
virtualEarthBingMap.propertiesDataArray = [];
},
//returns flyout info id
getFlyoutId : function(lat, longitude, rowCount){
if(rowCount == undefined){
rowCount = "";
}
try{
var flyoutId = "flyout"+rowCount+"[" + lat + "][" + longitude + "]";
return flyoutId
}catch(e){}
},
//Show info box
displayInfobox: function (e, rowCount) {
var disableToolTip = $('#disableToolTip').val();
if ((disableToolTip == undefined || disableToolTip == "" || disableToolTip == 'false') && e.targetType == 'pushpin') {
virtualEarthBingMap.hideInfobox();
if(rowCount == undefined){
rowCount = "";
}
var flyoutLat = $("input[name='pushpin-lat"+rowCount+"'][type='hidden']").val();
var flyoutLong = $("input[name='pushpin-long"+rowCount+"'][type='hidden']").val();
var flyoutId = virtualEarthBingMap.getFlyoutId(flyoutLat,flyoutLong, rowCount);
var infobox = document.getElementById(flyoutId);
$(infobox).css("display","inline");
$(infobox).css("z-index","10000");
$(infobox).css("position","absolute");
var pushpinPosition;
if(rowCount != "")
{
pushpinPosition = $('.pushpin'+rowCount).offset();
$(infobox).css("top",pushpinPosition.top + "px");
$(infobox).css("left",pushpinPosition.left + "px");
} else {
//original position
pushpinPosition = virtualEarthBingMap.map.tryLocationToPixel(e.target.getLocation(), virtualEarthBingMap.MM.PixelReference.page);
$(infobox).css("top",(pushpinPosition.y-40) + "px");
$(infobox).css("left",(pushpinPosition.x-5) + "px");
}
$('body').append(infobox);
setTimeout(virtualEarthBingMap.hideInfobox,12000); //hide infobox after 12 sec
}
},
//Hide infobox
hideInfobox: function () {
$('.display-off').css("display","none");
}
}//End virtualEarthBingMap
I am trying to set the bing map to zoom in on a location right now I am using this script to differentiate between single and multiple locations:
setMapView: function () {
if (virtualEarthBingMap.locations.length > 1) {
// set mapview for multiple hotels that dynamically sets the zoom so all pushpins are shown in ititial map window
virtualEarthBingMap.map.setView({bounds:virtualEarthBingMap.MM.LocationRect.fromLocations(virtualEarthBingMap.locations),padding:10});
} else {
// set mapview for single hotel
virtualEarthBingMap.map.setView({center:new Microsoft.Maps.Location(virtualEarthBingMap.propertiesDataArray[0].lat,virtualEarthBingMap.propertiesDataArray[0].longitude),zoom:15});
}
}
This is working on multiple locations but not on single locations. Anyone have any ideas?
A padding of 10 won't have an effect on the zoom level unless the map is less than 20 pixels wide. A simple solution is to set the zoom level instead. I recommend zoom level 15 or 16 for a single location.

Categories

Resources