map.fitbounds not doing anything - google-maps

I have a script which takes data from html and uses it to plot routes on a map. I'm trying to get it to take all the routes and zoom to show all of them. Here's the code:
var ombounds = new google.maps.LatLngBounds(); //bounds
for (var r=1; $("#master-master > div").length; r++)
{
// Add a placemark at the start of each route
var placemark_id = "#master-" + r + " > #placemarks-data > #placemark-0";
var markerParameters = {};
markerParameters.index = r-1;
markerParameters.total = $(placemark_id + " > .total").html();
markerParameters.mapData = $(placemark_id + " > .map").html();
markerParameters.instructionsData = $("#master-" + r + " > #snippet").html();
markerParameters.distanceData = $("#master-" + r + " > #distance").html();
markerParameters.durationData = $("#master-" + r + " > #duration").html();
markerParameters.titleData = $("#master-" + r + " > #title").html();
markerParameters.urltitleData = $("#master-" + r + " > #url-title").html();
markerParameters.imageData = $(placemark_id + " > .image").html();
$.OverMap.addMarker(markerParameters);
// Draw route
var points = new Array();
var pointsData = [];
var pointsData = $('#master-' + r + ' > #route-data').html();
if (pointsData != '')
{
var pointsArray = JSON.parse(pointsData);
for (var p=0; p<pointsArray.length; p++) {
var pt = new google.maps.LatLng(pointsArray[p][0], pointsArray[p][1]);
points.push(pt);
ombounds.extend(pt); //bounds
}
$.OverMap.drawRoute(points);
}
else $.OverMap.drawDirections({preserveViewport:false});
}
(map.getBounds()); //bounds
map.fitBounds(ombounds); //bounds
For some reason, map.fitBounds(ombounds) does nothing. The code still plots the routes, but I can't see what the bounds related functions are doing. I've added //bounds to all the lines related to the zooming - at the moment, they have no visible affect on the code's output. Anyone know where I'm going wrong?

When the preserveViewport option of the directions service is set to false, each call to the DirectionsRenderer will zoom and center the map on its result. If you want fitBounds to override it, you need to set that to true.

Related

How much faster could I make this script?

I have noticed that the script is significantly faster when I comment out the line that calls setValues(). Not that it's a super big issue, but I am interested in the different ways (if any) that I could speed the process up. If anyone has some insight, I would greatly appreciate it! It would also help me see where I could make similar optimizations in other parts of my script.
Here is the code in question:
// import new value(s)
if ((numRaw - numDk) > 0) {
var iDate;
var lastRow = getLastDataRow(earSheet, columnToLetter(earSheet.getRange("EAR_DATES_RNG").getColumn()));
var distName = impSheet.getRange("A1").getValue().toString();
var defaultDept = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("All Lists").getRange("A2").getValue().toString();
impData.forEach(function (entry) {
iDate = new Date(entry[0]);
var newEar = earSheet.getRange("A" + lastRow + ":G" + lastRow).getValues(); // init copy
if (currData.get(iDate.getTime()) == null) {
newEar[0][0] = entry[0];
newEar[0][1] = distName;
newEar[0][6] = entry[1];
newEar[0][3] = "Royalties";
newEar[0][4] = defaultDept;
newEar[0][5] = "NOT SPECIFIED";
earSheet.getRange("A" + lastRow + ":G" + lastRow).setValues(newEar);
Logger.log("ADDED: " + entry[1] + " to row: " + lastRow);
addedNewData++;
lastRow++;
}
else {
Logger.log("EXISTING DATA FOUND: " + currData.get(iDate.getTime()));
}
});
}
Using Matt and Cooper's suggestions, I came up with this revised code which is significantly faster:
if ((numRaw - numDk) > 0) {
var iDate;
var prevLastRow = getLastDataRow(earSheet, columnToLetter(earSheet.getRange("EAR_DATES_RNG").getColumn()));
var currLastRow = getLastDataRow(earSheet, columnToLetter(earSheet.getRange("EAR_DATES_RNG").getColumn()));
var rangeSize = numRaw;
var distName = impSheet.getRange("A1").getValue().toString();
var defaultDept = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("All Lists").getRange("A2").getValue().toString();
var newEar = earSheet.getRange("A" + prevLastRow + ":G" + (prevLastRow + rangeSize - 1)).getValues(); // init copy
impData.forEach(function (entry) {
iDate = new Date(entry[0]);
if (currData.get(iDate.getTime()) == null) {
newEar[currLastRow-2][0] = entry[0];
newEar[currLastRow-2][1] = distName;
newEar[currLastRow-2][6] = entry[1];
newEar[currLastRow-2][3] = "Royalties";
newEar[currLastRow-2][4] = defaultDept;
newEar[currLastRow-2][5] = "NOT SPECIFIED";
Logger.log("ADDED: " + entry[1] + " to row: " + currLastRow);
addedNewData++;
currLastRow++;
}
else {
Logger.log("EXISTING DATA FOUND: " + currData.get(iDate.getTime()));
}
});
earSheet.getRange("A" + prevLastRow + ":G" + (prevLastRow + rangeSize - 1)).setValues(newEar);
}```

Esri map with flex show name on navigator instead of coordinates

I am using com.esri.ags.components.directions on esri map and I added the stops by coordinates.
So how can I assign a name to the stop so it will be showing on screen and when printing instead of coordinates?
This is the code I added the stops into
var stop:DirectionsStop = mainUIComponent.myDirections.stopProvider[0];
stop.editable = false;
stop.searchTerm = UserSession.getCurrentUserDTO().dealerCoordinatesDTO.AddressLongitude + ","
+ UserSession.getCurrentUserDTO().dealerCoordinatesDTO.AddressLatitude;
var stopCount:int=1;
for( var i:int=0; i < customersToVisitsList.length; i++)
{
var point:DealerQuestMapPoint=new DealerQuestMapPoint(
customersToVisitsList[i].addressLongitude,customersToVisitsList[i].addressLatitude);
point.pointType="CUSTOMER";
point.targetObject=customersToVisitsList[i];
point.address = customersToVisitsList[i].address;
var imageTooltip:String//="Test";
customersToVisitsList[i].customerName.toString()
+"\n"+customersToVisitsList[i].address.toString()
+", "+customersToVisitsList[i].city.toString()
+"\n"+customersToVisitsList[i].state.toString()
+", "+customersToVisitsList[i].zip.toString();
renderMapPoint(mainUIComponent.customersLayer,
point,
customersToVisitsList[i].customer_id,
imageTooltip,
customersToVisitsList[i],
mainUIComponent.blueSymbol);
if(i==0)
{
var stop1:DirectionsStop = mainUIComponent.myDirections.stopProvider[1];
stop1.editable = true;
stop1.searchTerm = point.lon.toString() + "," + point.lat.toString();
stop1.name = customersToVisitsList[i].customerName.toString();
}
else
{
stopCount+=1;
var st:DirectionsStop = new DirectionsStop();
st.editable = true;
st.searchTerm = point.lon.toString() + "," + point.lat.toString();
st.name = customersToVisitsList[i].customerName.toString();
mainUIComponent.myDirections.stopProvider.addItem(st);
}
}
mainUIComponent.myDirections.getDirections();
I checked the documentation and I found nothing to do this because usually they deal with address but dealing with coordinates makes it a must to rename it to another name.
Screenshot of the map with coordinates written

How can I display a variable in a dynamic text field?

I have an input textfield on the screen and I have it set to the text that a user enters is saved as a variable and is later called upon o be displayed in a dynamic text box. It's kinda like a high score kind of system, but with multiple variables.
Here is the frame actions where the variables are being set (at least I think they are)
button.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
var data:String = username.text + " " + date.text + " " + company.text;
var file:FileReference = new FileReference();
file.save(data, username.text + " " + date.text + " " + company.text + ".txt");
}
button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame_8);
function fl_ClickToGoToNextFrame_8(event:MouseEvent):void
{
nextFrame();
}
var nameperson = username.text;
var dateperson = date.text;
var companyperson = company.text;
And are the actions where I'm trying to display the variables in another frame:
var nScore:Number = 0;
for(var i:Number = 0; i < aQuestions.length; i++)
{
if(aUserAnswers[i].toUpperCase() == aCorrectAnswers[i].toUpperCase())
{
nScore++;
}
if(i == aQuestions.length - 1)
{
score_txt.text = nScore.toString();
}
}
endresult_name.text = nameperson;
endresult_date.text = dateperson;
I believe the problem is that you set these variables straight when you get to your 1st frame (the text inputs are empty at that point). You need to set them after the user have filled them out and clicked on the button:
var nameperson:String;
var dateperson:String;
var companyperson:String;
function fl_MouseClickHandler(event:MouseEvent):void
{
var data:String = username.text + " " + date.text + " " + company.text;
var file:FileReference = new FileReference();
file.save(data, username.text + " " + date.text + " " + company.text + ".txt");
nameperson = username.text;
dateperson = date.text;
companyperson = company.text;
}

How do I format the directions output listing in Google Maps API V3?

I'm new to Google Maps API V3 and I have to use it to replace an older mapping app in one of our systems.
I've implemented a basic routing screen using the example at https://developers.google.com/maps/documentation/javascript/examples/directions-draggable
The basics are working well. The one thing that's bothering me is that I cannot find any clear discussion in the API of how to format the directions output listing. Nothing I've tried so far seems to affect it.
I'm simply doing a DirectionsRenderer.setPanel(div name) where the div has no properties other than a width of 1025px.
My chief irritations are that the directions themselves are only about 2/3 the width of the div and the text in the middle column looks like it's center justified. (The top and bottom of the list, the origin and destination addresses are the correct width.)
Is there any way to customize this or am I using too simple a model for my page?
The data used to render the directions panel is available in the result returned from the Directions Service, you can render it however you like by doing it manually.
Very simple example:
http://www.geocodezip.com/v3_directions_custom_icons_draggable.html
Custom Renderer:
function RenderCustomDirections(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
var detailsPanel = document.getElementById("direction_details");
startLocation = new Object();
endLocation = new Object();
summaryPanel.innerHTML = "";
detailsPanel.innerHTML = '<ul>';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
startLocation.marker = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
detailsPanel.innerHTML += "<li>"+steps[j].instructions;
var dist_dur = "";
if (steps[j].distance && steps[j].distance.text) dist_dur += " "+steps[j].distance.text;
if (steps[j].duration && steps[j].duration.text) dist_dur += " "+steps[j].duration.text;
if (dist_dur != "") {
detailsPanel.innerHTML += "("+dist_dur+")<br /></li>";
} else {
detailsPanel.innerHTML += "</li>";
}
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
detailsPanel.innerHTML += "</ul>"
polyline.setMap(map);
map.fitBounds(bounds);
endLocation.marker = createMarker(endLocation.latlng,"end",endLocation.address,"red");
// == create the initial sidebar ==
makeSidebar();
}
else alert(status);
}

Nine-patch images for web development [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I'm wondering if there is something like 9-patch in Android, but for web development?
Disclosure: I have no idea about web development at all, but I was curious to know if it exists. And a simple web search with the term 9-patch didn't bring up any related results, so I figured it has either another term or it doesn't exist or is not used widely enough.
Anyone knows?
Yes. It is used for border-image in CSS 3:
http://www.css3.info/preview/border-image/
http://www.w3.org/TR/css3-background/#border-images
If you're still interested I created a Javascript file that uses canvas to create real nine patch image support for the web. The open source project can be found here:
https://github.com/chrislondon/9-Patch-Image-for-Websites
Well, I took the trouble to correct deserts errors I found in the link above.
Knowing NinePath android is a useful tool adding dynamic painting and recognition of padding (which was missing in the previous pluying). I could add one few scripts for complete functionality.
Replace the following code in the library path9.js!
function NinePatchGetStyle(element, style)
{
if (window.getComputedStyle)
{
var computedStyle = window.getComputedStyle(element, "");
if (computedStyle === null)
return "";
return computedStyle.getPropertyValue(style);
}
else if (element.currentStyle)
{
return element.currentStyle[style];
}
else
{
return "";
}
}
// Cross browser function to find valid property
function NinePatchGetSupportedProp(propArray)
{
var root = document.documentElement; //reference root element of document
for (var i = 0; i < propArray.length; i++)
{
// loop through possible properties
if (typeof root.style[propArray[i]] === "string")
{
//if the property value is a string (versus undefined)
return propArray[i]; // return that string
}
}
return false;
}
/**
* 9patch constructer. Sets up cached data and runs initial draw.
* #param {Dom Element} div El Elemento dom en donde se pinta el ninepath
* #param {function} callback La funcion que se llamara cuando se termina
* la carga de la imagen y el pintado del elemento div.
* #returns {NinePatch} Un objeto nine path
*/
function NinePatch(div,callback)
{
this.div = div;
this.callback =callback;
this.padding = {top:0,left:0,right:0,bottom:0};
// Load 9patch from background-image
this.bgImage = new Image();
this.bgImage.src = NinePatchGetStyle(this.div, 'background-image').replace(/"/g, "").replace(/url\(|\)$/ig, "");
var este = this;
this.bgImage.onload = function()
{
este.originalBgColor = NinePatchGetStyle(este.div, 'background-color');
este.div.style.background = 'none';
// Create a temporary canvas to get the 9Patch index data.
var tempCtx, tempCanvas;
tempCanvas = document.createElement('canvas');
tempCanvas.width = este.bgImage.width;
tempCanvas.height = este.bgImage.height;
tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(este.bgImage, 0, 0);
// Obteniendo el padding lateral derecho
var dataPad = tempCtx.getImageData(este.bgImage.width-1,0,1,este.bgImage.height).data;
var padRight = este.getPadBorder(dataPad,este.bgImage.width,este.bgImage.height);
este.padding.top = padRight.top;
este.padding.bottom = padRight.bottom;
dataPad = tempCtx.getImageData(0,este.bgImage.height-1,este.bgImage.width,1).data;
var padBottom = este.getPadBorder(dataPad,este.bgImage.width,este.bgImage.height);
este.padding.left = padBottom.top;
este.padding.right = padBottom.bottom;
// Loop over each horizontal pixel and get piece
var data = tempCtx.getImageData(0, 0, este.bgImage.width, 1).data;
// Use the upper-left corner to get staticColor, use the upper-right corner
// to get the repeatColor.
var tempLength = data.length - 4;
var staticColor = data[0] + ',' + data[1] + ',' + data[2] + ',' + data[3];
var repeatColor = data[tempLength] + ',' + data[tempLength + 1] + ',' +
data[tempLength + 2] + ',' + data[tempLength + 3];
este.horizontalPieces = este.getPieces(data, staticColor, repeatColor);
// Loop over each horizontal pixel and get piece
data = tempCtx.getImageData(0, 0, 1, este.bgImage.height).data;
este.verticalPieces = este.getPieces(data, staticColor, repeatColor);
// use this.horizontalPieces and this.verticalPieces to generate image
este.draw();
este.div.onresize = function()
{
este.draw();
};
if(callback !== undefined)
{
if (typeof(callback) === "function")
callback();
}
};
}
// Stores the HTMLDivElement that's using the 9patch image
NinePatch.prototype.div = null;
// Padding
NinePatch.prototype.padding = null;
// Get padding
NinePatch.prototype.callback = null;
// Stores the original background css color to use later
NinePatch.prototype.originalBG = null;
// Stores the pieces used to generate the horizontal layout
NinePatch.prototype.horizontalPieces = null;
// Stores the pieces used to generate the vertical layout
NinePatch.prototype.verticalPieces = null;
// Stores the 9patch image
NinePatch.prototype.bgImage = null;
// Gets the horizontal|vertical pieces based on image data
NinePatch.prototype.getPieces = function(data, staticColor, repeatColor)
{
var tempDS, tempPosition, tempWidth, tempColor, tempType;
var tempArray = new Array();
tempColor = data[4] + ',' + data[5] + ',' + data[6] + ',' + data[7];
tempDS = (tempColor === staticColor ? 's' : (tempColor === repeatColor ? 'r' : 'd'));
tempPosition = 1;
for (var i = 4, n = data.length - 4; i < n; i += 4)
{
tempColor = data[i] + ',' + data[i + 1] + ',' + data[i + 2] + ',' + data[i + 3];
tempType = (tempColor === staticColor ? 's' : (tempColor === repeatColor ? 'r' : 'd'));
if (tempDS !== tempType)
{
// box changed colors
tempWidth = (i / 4) - tempPosition;
tempArray.push(new Array(tempDS, tempPosition, tempWidth));
tempDS = tempType;
tempPosition = i / 4;
tempWidth = 1;
}
}
// push end
tempWidth = (i / 4) - tempPosition;
tempArray.push(new Array(tempDS, tempPosition, tempWidth));
return tempArray;
};
NinePatch.prototype.getPadBorder = function(dataPad,width,height)
{
var staticRight = dataPad[0] + ',' + dataPad[1] + ',' + dataPad[2] + ',' + dataPad[3];
var pad={top:0,bottom:0};
// Padding para la parte superior
for (var i=0;i<dataPad.length;i+=4)
{
var tempColor = dataPad[i] + ',' + dataPad[i + 1] + ',' + dataPad[i + 2] + ',' + dataPad[i + 3];
if(tempColor !==staticRight)
break;
pad.top++;
}
// padding inferior
for (var i=dataPad.length-4;i>=0;i-=4)
{
var tempColor = dataPad[i] + ',' + dataPad[i + 1] + ',' + dataPad[i + 2] + ',' + dataPad[i + 3];
if(tempColor !==staticRight)
break;
pad.bottom++;
}
return pad;
};
// Function to draw the background for the given element size.
NinePatch.prototype.draw = function()
{
var dCtx, dCanvas, dWidth, dHeight;
if(this.horizontalPieces === null)
return;
dWidth = this.div.offsetWidth;
dHeight = this.div.offsetHeight;
dCanvas = document.createElement('canvas');
dCtx = dCanvas.getContext('2d');
dCanvas.width = dWidth;
dCanvas.height = dHeight;
var fillWidth, fillHeight;
// Determine the width for the static and dynamic pieces
var tempStaticWidth = 0;
var tempDynamicCount = 0;
for (var i = 0, n = this.horizontalPieces.length; i < n; i++)
{
if (this.horizontalPieces[i][0] === 's')
tempStaticWidth += this.horizontalPieces[i][2];
else
tempDynamicCount++;
}
fillWidth = (dWidth - tempStaticWidth) / tempDynamicCount;
// Determine the height for the static and dynamic pieces
var tempStaticHeight = 0;
tempDynamicCount = 0;
for (var i = 0, n = this.verticalPieces.length; i < n; i++)
{
if (this.verticalPieces[i][0] === 's')
tempStaticHeight += this.verticalPieces[i][2];
else
tempDynamicCount++;
}
fillHeight = (dHeight - tempStaticHeight) / tempDynamicCount;
// Loop through each of the vertical/horizontal pieces and draw on
// the canvas
for (var i = 0, m = this.verticalPieces.length; i < m; i++)
{
for (var j = 0, n = this.horizontalPieces.length; j < n; j++)
{
var tempFillWidth, tempFillHeight;
tempFillWidth = (this.horizontalPieces[j][0] === 'd') ?
fillWidth : this.horizontalPieces[j][2];
tempFillHeight = (this.verticalPieces[i][0] === 'd') ?
fillHeight : this.verticalPieces[i][2];
// Stretching :
if (this.verticalPieces[i][0] !== 'r') {
// Stretching is the same function for the static squares
// the only difference is the widths/heights are the same.
dCtx.drawImage(
this.bgImage,
this.horizontalPieces[j][1], this.verticalPieces[i][1],
this.horizontalPieces[j][2], this.verticalPieces[i][2],
0, 0,
tempFillWidth, tempFillHeight);
} else {
var tempCanvas = document.createElement('canvas');
tempCanvas.width = this.horizontalPieces[j][2];
tempCanvas.height = this.verticalPieces[i][2];
var tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(this.bgImage,
this.horizontalPieces[j][1], this.verticalPieces[i][1],
this.horizontalPieces[j][2], this.verticalPieces[i][2],
0, 0,
this.horizontalPieces[j][2], this.verticalPieces[i][2]);
var tempPattern = dCtx.createPattern(tempCanvas, 'repeat');
dCtx.fillStyle = tempPattern;
dCtx.fillRect(
0, 0,
tempFillWidth, tempFillHeight);
}
// Shift to next x position
dCtx.translate(tempFillWidth, 0);
}
// shift back to 0 x and down to the next line
dCtx.translate(-dWidth, (this.verticalPieces[i][0] === 's' ? this.verticalPieces[i][2] : fillHeight));
}
// store the canvas as the div's background
var url = dCanvas.toDataURL("image/png");
var tempIMG = new Image();
var _this = this;
tempIMG.onload = function(event)
{
_this.div.style.background = _this.originalBgColor + " url(" + url + ") no-repeat";
};
tempIMG.src = url;
};
The usage is the following:
var elemDom = document.getElementById("idDiv");
var background = "border.9.png";
if (background.match(/\.9\.(png|gif)/i)) // Es nine path?
{
elemDom.style.backgroundRepeat = "no-repeat";
elemDom.style.backgroundPosition = "-1000px -1000px";
elemDom.style.backgroundImage = "url('"+background+"')";
var ninePatch = new NinePatch(elemDom,function()
{
elemDom.style.paddingLeft = ninePatch.padding.left;
elemDom.style.paddingTop = ninePatch.padding.top;
elemDom.style.paddingRight = ninePatch.padding.right;
elemDom.style.paddingBottom = ninePatch.padding.bottom;
});
}
I forked https://github.com/chrislondon/9-Patch-Image-for-Websites and fixed the bugs based on the above comments. Now the 9-Patch javascript works well. Please check out https://github.com/blackmonkey/jQuery-9-Patch