Setting the map scale

655
6
12-21-2020 02:18 PM
NovicaJ
Occasional Contributor

I have a very basic scenario where my map scale is either 1:1000 or 1:2500, so I made two radio buttons. Something like this

<div class="col-sm-6">
                <label for="">Scale</label>
                <select class="form-control" id="scale" name="scale">
                    <option value="1" selected>1:1000</option>
                    <option value="2">1:2500</option>
                </select>
            </div>

Then, depending on the option selected, I either set a global variable to 1000 or 2500, like so

//global variable
 var sentScale;
 
 //check which button is clicked and set the variable with the selected value
 var scaleDiv = $("#scale option:selected").val();

            if (scaleDiv == 1) {
                sentScale = 1000;
            } else {
                sentScale = 2500;
            }

And then, I set the map scale, like so

// ZOOM TO ROUTE
                    function zoomToRoute(features) {

                        var map = this.map;
                        map.graphics.clear();

                        var pointSymbolNew = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 255, 255]), 1), new Color([255, 0, 127, 1]));
                        var selectedFeature = features.features;
                        selectedFeature[0].setSymbol(pointSymbolNew);
                        map.graphics.add(selectedFeature[0]);

                        map.setScale(sentScale);
                        map.centerAt(selectedFeature[0].geometry);
                        setTimeout(printImage, 5000);
                    }

And then I use printTask to print out the map

// PRINT RESULT
                    function printResult(evt) {
                        imageUrl = evt.url;
                        setCookie('imageUrl', imageUrl, 1);

                        if (reportType == 1) {

                            printReport();
                        }
                        if (reportType == 2) {
                            var printTaskLegend;
                            var printPars = new PrintParameters();
                            printPars.map = map;

                            if (sentScale == 1000) {

                                printTaskLegend = new PrintTask('http://10.0.0.10:6080/arcgis/rest/services/Print_legend_included/GPServer/Export%20Web%20Map');
                                printPars.map = map;
                            }
                            else if (sentScale == 2500) {

                                printTaskLegend = new PrintTask('http://10.0.0.10:6080/arcgis/rest/services/Print_legend_included/GPServer/Export%20Web%20Map');
                                printPars.map = map;
                            }

                            var template = new PrintTemplate();
                            template.format = 'JPG';
                            template.layout = 'Print_legend_included';
                            template.preserveScale = true;
                            printPars.template = template;
                            printTaskLegend.execute(printPars, printImageLegend);
                        }

So I am printing the report, everything is fine and then the clients get back in touch with me, saying the scale is incorrect. 1:1000 is incorrect, 1:2500 is incorrect. Is this not a good way to set the map scale?

Tags (2)
0 Kudos
6 Replies
IanPeebles
Regular Contributor

Hello, we have created a zoom to scale tool within our organization, but we allow for an input box where you can type in the scale, then zoom to it on the map.  perhaps you can use similar logic or get an idea from this code snippet I will provide?

A Preview of the Zoom the Scale Tool within an Application:

IanPeebles_2-1608659409022.png

 

The CODE in JS and HTML:

// ***********************************************************************
// * Zoom to Scale - START *
// ***********************************************************************
// Execute Zoom to Scale when Button is Clicked
on(dom.byId("zoomToScaleBtn"), "click", zoomToScale);

// Zoom to Scale Function
function zoomToScale () {
if (dom.byId("zoomToScaleValue").value == "") {
alert("You must enter in a scale value");
}
else
{
// Return Scale Value - Calculation (/12) based on Feet not Meters
var scaleValue = (dom.byId("zoomToScaleValue").value)*12;
map.setScale(scaleValue);
var scaleValueFeet = (scaleValue/12);
console.log("The map scale is 1:" + scaleValue);
console.log("Map Scale in Feet 1 inch = " + scaleValueFeet + " feet");
}
}

// Return Map Scale Results to Application - Calculation (/12) based on Feet NOT Meters
map.on("zoom-end", function() {
var returnZoomResult = document.getElementById("zoomToScaleResults");
var scale = map.getScale()/12;
var roundScale = Math.round(scale);
returnZoomResult.innerHTML = roundScale + " feet";
});
// ***********************************************************************
// * Zoom to Scale - END *
// ***********************************************************************

 

<!-- ************************************ -->
<!-- * ZOOM TO SCALE                           * -->
<!-- ************************************ -->
<div id="zoomToScaleTextBoxFrame">
<input type="search" id="zoomToScaleValue" placeholder="Zoom to Scale (Feet)" onkeypress="if (event.keyCode == 13) document.getElementById('zoomToScaleBtn').click()" />
<button id="zoomToScaleBtn" title="Zoom to Scale"></button>
</div>

 

Print layout scale:

IanPeebles_1-1608659273743.png

 

I am wondering if you can choose the scale within the map first, then run the print task?  Or are you wanting to choose the scale when you are initiating the print task?

0 Kudos
NovicaJ
Occasional Contributor

Ian,

Yes, I first choose the scale then I set the map scale and they I run printTask. This is what my form /view looks like, the highlighted in red is the scale for the map.

NovicaJ_0-1608668450239.png

First comes the scale dropdown

<div class="col-sm-6">
                <label for="">Размер</label>
                <select class="form-control" id="scale" name="scale">
                    <option value="1" selected>1:1000</option>
                    <option value="2">1:2500</option>
                </select>
            </div>

then I check the dropdown option which was clicked

var scaleDiv = $("#scale option:selected").val();

            if (scaleDiv == 1) {
                //sentScale = "1000";
                sentScale = 1000;
            } else {
                //sentScale = "2500";
                sentScale = 2500;
            }

and I set the scale value according to which option from the dropdown was clicked. Then I execute the printMap() function which contains zoomToRoute

function printMap() {
            require(["dojo/on", "esri/config", "esri/tasks/QueryTask", "esri/tasks/query", 'esri/symbols/SimpleMarkerSymbol', "esri/symbols/SimpleLineSymbol", "esri/Color", 'esri/geometry/Extent', "esri/tasks/PrintTask", "esri/tasks/PrintParameters", "esri/tasks/PrintTemplate", "dojo/domReady!"],
                function (on, esriConfig, QueryTask, Query, SimpleMarkerSymbol, SimpleLineSymbol, Color, Extent, PrintTask, PrintParameters, PrintTemplate) {
                    console.log("globalParcel :: " + globalParcel + " reportType :: " + reportType + " globalScale :: " + sentScale);
                    //var queryTask = new QueryTask("http://app.gdi.mk:6080/arcgis/rest/services/karpos/Karpos_Vector_Izvodi/MapServer/1");
                    var queryTask = new QueryTask("http://10.0.0.10:6080/arcgis/rest/services/Karpos_Vector_Izvodi/MapServer/1");
                    var query = new Query();
                    query.where = "code ='" + globalParcel + "'";
                    query.outSpatialReference = map.spatialReference;
                    query.returnGeometry = true;
                    query.outFields = ["*"];
                    queryTask.execute(query).then(zoomToRoute);


                    // ZOOM TO ROUTE
                    function zoomToRoute(features) {

                        var map = this.map;
                        map.graphics.clear();

                        var pointSymbolNew = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 255, 255]), 1), new Color([255, 0, 127, 1]));
                        var selectedFeature = features.features;
                        selectedFeature[0].setSymbol(pointSymbolNew);
                        map.graphics.add(selectedFeature[0]);

                        map.setScale(sentScale);
                        console.log("map.setScale(sentScale)", sentScale)
                        map.centerAt(selectedFeature[0].geometry);
                        setTimeout(printImage, 5000);
                    }
                    // ZOOM TO ROUTE
}

and in the zoomToRoute, I set the map scale with map.setScale(sentScale);

0 Kudos
IanPeebles
Regular Contributor

What coordinate system are you using?

0 Kudos
NovicaJ
Occasional Contributor

The coordinate system is 6316, that's what we use in my country. 

0 Kudos
IanPeebles
Regular Contributor

Here is what I came up with to set the map scale when using the choice list:

Choice List from Application:

IanPeebles_0-1608736384111.png

 

JavaScript Code:

IanPeebles_1-1608736400212.png

IanPeebles_5-1608736645366.png

 

HTML Code:

IanPeebles_2-1608736414882.png

 

When choosing the option, then the mouse is up, the zoom to scale will execute. The map changes zoom.

I added console statements to track the changing map scale.  Here are examples of those that returned in the console.log:

For 1000 Scale:

IanPeebles_3-1608736497779.png

 

For 2500 Scale:

IanPeebles_4-1608736510224.png

Will something like that work?  I don't think the map scale will change on the print layout.  We use a zoom tool where you type in the scale and then a zoom occurs on the map.  When we go to print the layout, the map scale is preserved.

 

 

0 Kudos
NovicaJ
Occasional Contributor

 

@model ModelLayer.Models.ReportModel

@{
    ViewData["Title"] = "Извештај";
}

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

<script src="~/js/bootstrap.min.js"></script>
<link href="~/css/bootstrap.min.css" rel="stylesheet" />

<link href="http://kendo.cdn.telerik.com/2020.2.513/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://kendo.cdn.telerik.com/2020.2.513/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://kendo.cdn.telerik.com/2020.2.513/js/kendo.all.min.js"></script>
<script src="~/js/kendo.aspnetmvc.min.js"></script>

<!--If Kendo is used it should be added before the report viewer.-->
<script src="~/Reports/telerikReportViewer-14.2.20.1021.min.js"></script>
<script src="~/Reports/telerikReportViewer.kendo-14.2.20.1021.min.js"></script>

<script>
    window.rootUrl = '@Url.Content("~/")';
</script>

<style>
    #reportViewer1 {
        position: absolute;
        left: 5px;
        right: 5px;
        top: 5px;
        bottom: 5px;
        overflow: hidden;
        font-family: Verdana, Arial;
        padding-left: 19%;
        display: none
    }

    #reportForm {
        margin-left: 16%;
        box-shadow: 10px 10px 25px 0px rgba(0,0,0,0.75);
        border-radius: 5px;
    }

    #loader {
        position: fixed;
        top: 50%;
        right: 50%;
        max-width: 20%;
        max-height: 20%;
        background-color: #fff;
        background-image: url('~/img/loading.gif');
        background-repeat: no-repeat;
        background-position: center;
        z-index: 10000000;
        opacity: 0.4;
        filter: alpha(opacity=40); /* For IE8 and earlier */
    }

    .k-widget .k-datepicker {
        width: 100%;
    }
</style>

<img src="~/img/loading.gif" id="loader" style="display:none" />
<link rel="stylesheet" href="http://js.arcgis.com/3.32/esri/css/esri.css">
<script src="http://js.arcgis.com/3.32/"></script>

<script>
    /*
       This script is used to create the map on page load.
       Layers are added to the map and the rest of the action is completed on Print button click
    */


    var map;
    var imageUrl, imageLegendUrl;
    var minParc, fullP, sentScale, reportType, globalParcel;
    var mainReportParameters = {};
    var mainReport;
    var documentType;
    var returnScaleValue;


    require(["esri/map",
        "esri/config",
        "esri/dijit/Basemap",
        "esri/dijit/BasemapLayer",
        "esri/layers/ArcGISTiledMapServiceLayer",
        "esri/layers/ArcGISDynamicMapServiceLayer",
        "esri/tasks/QueryTask", "esri/tasks/query",
        "esri/symbols/SimpleFillSymbol",
        "esri/symbols/SimpleLineSymbol", "esri/Color", "esri/graphic",
        'esri/symbols/SimpleMarkerSymbol',
        'dojo/_base/array',
        'esri/geometry/Extent',
        "esri/dijit/Print",
        "esri/tasks/PrintTemplate",
        "dojo/dom", "esri/tasks/PrintTask", "esri/tasks/PrintParameters",
        "dojo/on",
        "dojo/domReady!"],
        function (Map, esriConfig, Basemap, BasemapLayer, ArcGISTiledMapServiceLayer, ArcGISDynamicMapServiceLayer, QueryTask, Query, SimpleFillSymbol, SimpleLineSymbol, Color, Graphic, SimpleMarkerSymbol, array, Extent, Print, PrintTemplate, dom, PrintTask, PrintParameters, on) {

            map = new Map("map", {
                basemap: new Basemap({
                    layers: [new BasemapLayer({
                        url: 'http://10.0.0.10/arcgis/rest/services/Podlogi_Izvodi_500/MapServer'
                    })]
                }),
                extent: new Extent({
                    'xmin': 7530850.8094923375,
                    'ymin': 4647910.133863028,
                    'xmax': 7536270.404088697,
                    'ymax': 4655172.52276435,
                    'spatialReference': {
                        'wkid': 6316
                    }
                }),
                sliderStyle: 'small',
                zoom: 5,

            });

            
            var secondLayer = new ArcGISDynamicMapServiceLayer("http://10.0.0.10:6080/arcgis/rest/services/Karpos_Vector_Izvodi/MapServer", {
                "opacity": 1
            });

            map.addLayer(secondLayer);
            map.on("load", selectRoute);

            function selectRoute() {
                console.log("Security patch #523532.12");
            }
        }
    );

    $(document).ready(function () {

        // - button for report printing
        clicks = function (e) {

            $("#loader").show();
            $("#reportForm").hide();
            reportType = $("input[name='reportButton']:checked").val();
            globalParcel = ($("#buildParcelID").val()).trim();
            printMap();
        }
        // - button for report printing


        selectScale = function () {
            returnScaleValue = document.getElementById("chooseScale").value;

            map.setScale(returnScaleValue);
            console.log("The returned scale value is:", returnScaleValue);
        }


        function printMap() {
            require(["dojo/on", "esri/config", "esri/tasks/QueryTask", "esri/tasks/query", 'esri/symbols/SimpleMarkerSymbol', "esri/symbols/SimpleLineSymbol", "esri/Color", 'esri/geometry/Extent', "esri/tasks/PrintTask", "esri/tasks/PrintParameters", "esri/tasks/PrintTemplate", "dojo/domReady!"],
                function (on, esriConfig, QueryTask, Query, SimpleMarkerSymbol, SimpleLineSymbol, Color, Extent, PrintTask, PrintParameters, PrintTemplate) {
                    console.log("globalParcel :: " + globalParcel + " reportType :: " + reportType + " globalScale :: " + sentScale);
                    var queryTask = new QueryTask("http://app.gdi.mk:6080/arcgis/rest/services/karpos/Karpos_Vector_Izvodi/MapServer/1");
                    var query = new Query();
                    query.where = "code ='" + globalParcel + "'";
                    query.outSpatialReference = map.spatialReference;
                    query.returnGeometry = true;
                    query.outFields = ["*"];
                    queryTask.execute(query).then(zoomToRoute);


                    // ZOOM TO ROUTE
                    function zoomToRoute(features) {

                        var map = this.map;
                        map.graphics.clear();

                        var pointSymbolNew = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255, 255, 255]), 1), new Color([255, 0, 127, 1]));
                        var selectedFeature = features.features;
                        selectedFeature[0].setSymbol(pointSymbolNew);
                        map.graphics.add(selectedFeature[0]);

                        map.setScale(returnScaleValue)
                        console.log("map.setScale(returnScaleValue)", returnScaleValue)

                        //map.setScale(sentScale);
                        //console.log("map.setScale(sentScale)", sentScale)
                        map.centerAt(selectedFeature[0].geometry);
                        setTimeout(printImage, 5000);
                    }
                    // ZOOM TO ROUTE

                   

                    // SET COOKIE
                    function setCookie(cname, cvalue, exdays) {
                        var d = new Date();
                        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
                        var expires = "expires=" + d.toGMTString();
                        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
                    }
                    // SET COOKIE

                    // PRINT IMAGE
                    function printImage() {

                        var printTask;
                        var params = new PrintParameters();
                       
                            printTask = new PrintTask('http://10.0.0.10:6080/arcgis/rest/services/Print_legend_included/GPServer/Export%20Web%20Map');
                            params.map = map;


                        var template = new PrintTemplate();
                        template.format = 'JPG';
                        template.layout = 'MAP_ONLY';
                        template.preserveScale = false;
                        params.template = template;

                        printTask.execute(params, printResult);
                    }
                    // PRINT IMAGE



                    // PRINT RESULT
                    function printResult(evt) {
                        imageUrl = evt.url;
                        setCookie('imageUrl', imageUrl, 1);

                        if (reportType == 1) {

                            printReport();
                        }
                        if (reportType == 2) {
                            var printTaskLegend;
                            var printPars = new PrintParameters();
                            printPars.map = map;

                            printTaskLegend = new PrintTask('http://10.0.0.10:6080/arcgis/rest/services/Print_legend_included/GPServer/Export%20Web%20Map');
                            params.map = map;

                            var template = new PrintTemplate();
                            template.format = 'JPG';
                            template.layout = 'Print_legend_included';
                            template.preserveScale = true;
                            printPars.template = template;
                            printTaskLegend.execute(printPars, printImageLegend);

                        }
                    }
                    // PRINT RESULT


                    // PRINT IMAGE LEGEND
                    function printImageLegend(evt) {

                        imageLegendUrl = evt.url;
                        setCookie('imageLegendUrl', imageLegendUrl, 1);
                        printReport();
                    }
                    // PRINT IMAGE LEGEND

                });
        }


        // PRINT REPORT FUNCTION
        function printReport() {
            
            var trafficValString = 'Паркирање во рамките на сопствена парцела'
            if ($("#trafficConditionsID").val() == '') {
                trafficVal = trafficValString;
            } else {
                trafficVal = $("#trafficConditionsID").val();
            }

            var miscValString = 'Овој извод е основа за изработка на основен проект/архитектонско - урбанистички проект, кој пак е потребен во постапката за добивање одобрение за градење. Изработката на проектантската документација да е во согласност со законската и подзаконската регулатива од областа.'
            if ($("#miscelanousID").val() == '') {
                miscVal = miscValString;
            } else {
                miscVal = $("#miscelanousID").val();
            }

            if (reportType == 1) {

                documentType = "KarposSingleReportFINAL.trdp"
                mainReportParameters = {
                    "reportNumberID_par": $("#reportNumberID").val(),
                    "dateID_par": $("#dateID").val(),
                    "planNumberID_par": $("#planNumberID").val(),
                    "dupDescription_par": $("#DUPid").val(),
                    "dupDecision_par": $("#odlukaDup").val(),
                    "dupDate_par": $("#datumDup").val(),
                    "klasaNamena_par": $("#klasaNam").val(),
                    "buildParcel_par": minParc,
                    "street_par": $("#streetNameID").val(),
                    "houseNumber_par": $("#houseNumberID option:selected").val(),
                    "municipality_par": $("#KBRid").val(),
                    "detailsDocument_par": $("#detailsDocumentID").val(),
                    "municipalParcel_par": $("#municipalParcelID").val(),
                    "scale_par": $("#scale option:selected").text(),
                    "imageUrl_par": readCookie("imageUrl")
                }
            }
            if (reportType == 2) {

                documentType = "KarposDoubleReport.trdp"
                mainReportParameters = {
                    "reportNumberID_par": $("#reportNumberID").val(),
                    "dateID_par": $("#dateID").val(),
                    "planNumberID_par": $("#planNumberID").val(),
                    "dupDescription_par": $("#DUPid").val(),
                    "dupDecision_par": $("#odlukaDup").val(),
                    "dupDate_par": $("#datumDup").val(),
                    "klasaNamena_par": $("#klasaNam").val(),
                    "buildParcel_par": minParc,
                    "street_par": $("#streetNameID").val(),
                    "houseNumber_par": $("#houseNumberID option:selected").val(),
                    "municipality_par": $("#KBRid").val(),
                    "detailsDocument_par": $("#detailsDocumentID").val(),
                    "municipalParcel_par": $("#municipalParcelID").val(),
                    "scale_par": $("#scale option:selected").text(),
                    "urbanistickaParc_par": $("#urbanistickaParcela").val(),
                    "povrsinaUrbParc_par": $("#povrsinaUrbParc").val() + " м2",
                    "povrsinaGabarit_par": $("#povrsinaGabarit").val() + " м2",
                    "procentIzgradenost_par": $("#procentIzgradenost").val() + "%",
                    "maxIzgPovr_par": $("#maxIzgPovr").val() + " м2",
                    "koefIsko_par": $("#koefIsko").val(),
                    "maxDozH_par": $("#maxDozH").val() + " м",
                    //"maxHSleme_par": maxSleme,
                    "brojParkingMesta_par": $("#brParkingMesta").val(),
                    "drUslovi_par": miscVal,
                    "soobUslovi_par": trafficVal,
                    "imageUrl_par": readCookie("imageUrl"),
                    "imageLegendUrl_par": readCookie("imageLegendUrl")
                }
            }
            $("#reportViewer1").show();
            $("#loader").hide();


            $("#reportViewer1").telerik_ReportViewer({

                serviceUrl: "/karposreports/api/reports/",
                reportSource: {
                    report: documentType,
                    parameters: mainReportParameters
                },
                viewMode: telerikReportViewer.ViewModes.INTERACTIVE,
                scaleMode: telerikReportViewer.ScaleModes.SPECIFIC,
                scale: 1.0,
                enableAccessibility: true,
                sendEmail: { enabled: false },
                ready: function () {
                    //this.refreshReport();
                },
            });
        }
        // PRINT REPORT FUNCTION

    });
</script>
<div>
    <div>
        <div class="sidebar" data-color="azure" data-background-color="white" />
        <!--
            Tip 1: You can change the color of the sidebar using: data-color="purple | azure | green | orange | danger"

            Tip 2: you can also add an image using data-image tag
        -->
        <div class="logo">
            <a href="https://karpos.gov.mk/" class="simple-text logo-normal">
                Општина Карпош
            </a>
        </div>
        <div class="sidebar-wrapper">
            <ul class="nav">
                <li class="nav-item active">
                    <a class="nav-link" asp-controller="DUP" asp-action="PrintReport">

                        <i class="fa fa-plus-circle" aria-hidden="true"></i>
                        <span>Подготви извештај</span>
                    </a>
                </li>
                <li class="nav-item ">
                    <a class="nav-link" href="http://62.162.113.130:6080/karposgis/">
                        <i class="material-icons">content_paste</i>
                        <p>ГИС Прегледник</p>
                    </a>
                </li>
            </ul>
        </div>
    </div>
</div>

<div id="reportForm">
        
            <div class="col-sm-6">
                <label for="">Размер</label>
                <select class="form-control" id="chooseScale" name="scale" onmouseup="selectScale()">
                    <option value="1000" selected>1:1000</option>
                    <option value="2500">1:2500</option>
                </select>
            </div>
        </div>        
</div>

<div id="reportViewer1" class="k-widget">
    loading...
</div>

 

 

I took your code, placed it inside my view. I get the values, they are correct but the printTask is not working now for some reason. Also, it's kind of an issue that initially the dropdown value is 1:1000 but unless I actually click the dropdown, the value is empty. 

0 Kudos