Your Location is: Home > Php

Fix Leaflet not including picture on a generated map

From: Albania View: 4122 Mark Bottom 

Question

I am using leaflet to create a map with a picture on it. The picture is generated from gda2tiles.py from a .tif file. The picture is currently generated successfully and it can be viewed when I open the link generated. The problem that I am having is that the map being created does not include the picture. There is a select box with the option to display or not the picture and it has the correct picture information, but the actual picture is not being added.

There are no error/warnings messages.

generate.php

<?php
require_once("SetFilePath.php");
require_once("CommonFunctions.php");
require_once("SetDBConnection.php");

$pageID = $_GET["pageid"];
$groups = $_REQUEST["groups"];
$projectID = $_GET["project"];
$pageTitle = $_GET["name"];
$center = $_GET["center"];
$zoom = $_GET["zoom"];
$minZoom = $_GET["minZoom"];
$maxZoom = $_GET["maxZoom"];

$con = SetDBConnection();

if(mysqli_connect_errno())
{
    echo "Failed to connect to database server: ".mysqli_connect_error();
}
else
{
    $deleteSQL =  "delete from visualization_project where id = $pageID";
    mysqli_query($con,$deleteSQL);

    $sql =  "select imagery_product.*, flight.Date as Date, product_type.Type as producttype ".
        "from imagery_product, flight, product_type ".
        "where flight.Project = $projectID and imagery_product.Flight = flight.ID ".
        "and imagery_product.Type = product_type.ID and imagery_product.Status = 'Finished' ".
        "order by Filename";

    $folderPath = SetTempFolderLocalPath().FormatFileName($pageTitle);
    if(!file_exists($folderPath)){
        if (!mkdir($folderPath, 0777, true)) {
            die('Failed to create folders...');
        }
    }

    $pagepath = $folderPath."/index.html";
    $viewPath = str_replace("/var/www/html/wordpress/","http://test.org/",$pagepath);

    $addSQL =   "insert into visualization_project (Name, Project, Path) ".
        "values ('$pageTitle', $projectID, '$viewPath')";
    mysqli_query($con,$addSQL);
    $vProjectID = $con->insert_id;

    $result = mysqli_query($con,$sql);
    $productList = array();
    while($row = mysqli_fetch_assoc($result)) {
        $productList[] = $row;
    }
    $zIndex = 50;

    $layerText = "";
    $overLayerText = "";

    $firstLayer = true;

    foreach ($groups as $group) {
        $idList = preg_split("@;@", $group["IDs"], NULL, PREG_SPLIT_NO_EMPTY);
        if (count($idList) > 0){

            $addSQL =   "insert into visualization_group (Name, Type, Project) ".
                "values ('".$group["GroupName"]."', '". $group["Type"] ."',$vProjectID)";
            mysqli_query($con,$addSQL);
            $vGroupID = $con->insert_id;

            $groupText =    "{\n".
                "\tgroup: '".$group["GroupName"]."',\n".
                "\tlayers: [\n";

            foreach ($idList as $id){
                foreach ($productList as $product){
                    if($product["ID"] == $id){

                        $addSQL =   "insert into visualization_layer (Layer, GroupID) ".
                            "values ($id, $vGroupID)";
                        mysqli_query($con,$addSQL);

                        $boundaryText = "";

                        if ($product["Boundary"] != ""){
                            $bounds = explode(";", $product["Boundary"]);
                            $boundaryText = ", bounds: L.latLngBounds([";
                            foreach ($bounds as $bound){
                                $point = "L.latLng(".$bound."),";
                                $boundaryText .= $point;
                            }


                            $boundaryText = rtrim($boundaryText,",")."])";
                        }

                        if ($product["producttype"] == "V") {
                            $base_json_name = str_ireplace(".geojson","",$product["FileName"]);
                            $layerName = "layer_".$base_json_name;
                            $paneName  =  "pane_".$base_json_name;

                            $layer1 = "map.createPane('".$paneName."'); \n";
                            $layer2 = "map.getPane('".$paneName."').style.zIndex = ".$zIndex."; \n";
                            $layer3 = "map.getPane('".$paneName."').style.pointerEvents = 'none'; \n";
                            $layer4 = "var ".$layerName." = new L.GeoJSON.AJAX('".$product["UploadFolder"]."/".$product["FileName"]."', {pane: '".$paneName."'}); \n";

                            $layer = $layer1.$layer2.$layer3.$layer4;

                        } else {

                            $layerName = "layer_".str_ireplace(".tif","",$product["FileName"]);
                            $layer =    "var ".$layerName." = L.tileLayer('".$product["TMSPath"].
                                "', {tms: true, zIndex: ".$zIndex.$boundaryText."}); \n";

                        }

                        $layerText .= $layer;

                        if ($firstLayer){
                            $activeText = "active: 'true',\n";
                            $firstLayer = false;
                        } else {
                            $activeText = "";
                        }

                        $groupText .=   "\t\t{\n".
                            "\t\t\tname: '".str_replace("-","/",$product["Date"])."',\n".
                            $activeText.
                            "\t\t\tlayer: ".$layerName."\n".
                            "\t\t},\n";

                        $zIndex++;
                    }
                }
            }

            $groupText .=       "\t]\n".
                "},\n";

            $overLayerText.= $groupText;
        }
    }

    $templatePath = getcwd()."/page_template.html";
    $pageContent = file_get_contents($templatePath);
    $pageContent = str_replace("#PAGE-TITLE#",$pageTitle, $pageContent);
    $pageContent = str_replace("#PROJECT-CENTER#",$center, $pageContent);
    $pageContent = str_replace("#DEFAULT-ZOOM#",$zoom, $pageContent);
    $pageContent = str_replace("#MIN-ZOOM#",$minZoom, $pageContent);
    $pageContent = str_replace("#MAX-ZOOM#",$maxZoom, $pageContent);
    $pageContent = str_replace("#LAYERS#",$layerText, $pageContent);
    $pageContent = str_replace("#OVER-LAYERS#",$overLayerText, $pageContent);

    echo $pageContent;

    $file = fopen($pagepath, "w") or die("Unable to open file!");
    fwrite($file, $pageContent);
    fclose($file);

    echo $viewPath;
}
?>

File generated

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>test4bigfile</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<link rel="stylesheet" href="/css/leaflet.css" />
<link rel="stylesheet" href="/css/leaflet-panel-layers.css" />

<style>
    body { margin:0; padding:0; }
    #map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>

<body>
<br />
<div id="map"></div>

<script src="/js/leaflet.js"></script>
<script src="/js/leaflet-panel-layers.js"></script>
<script src="/js/jquery.min.js"></script>
<script src="/js/leaflet-ajax/dist/leaflet.ajax.js"></script>
<script src="/js/legend.js"></script>
<link rel="stylesheet" href="/css/legend.css" />

<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-74689450-1', 'auto');
    ga('send', 'pageview');
</script>

<script>
    var map = L.map('map', {
        center: L.latLng([27.7823,-97.5606]),
        zoom: 19,
        minZoom: 17,
        maxZoom: 25,
        attributionControl: false
    });

    var osm_map = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
        zIndex: 0
    });

    var mapbox = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
        attribution: 'Imagery from <a href="https://mapbox.com/about/maps/">MapBox</a> &mdash; Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
        subdomains: 'abcd',
        id: 'mapbox.satellite',
        accessToken: 'pk.eyJ1IjoiaGFtZG9yaSIsImEiOiJjaWZmZzBwbjI4ZGdqc21seDFhOHA5dGcxIn0.4An46DNTDt97W992MRRWoQ',
        maxNativeZoom: 19,
        zIndex: 0
    });


    // Layers
    var layer_bigfgiletest4 = L.tileLayer('https://img.00w5.com/2020-11-19/{y}.png', {tms: true, zIndex: 50, bounds: L.latLngBounds([L.latLng(30.534394444444,-96.447652777778),L.latLng(30.534305555556,-96.443116666667),L.latLng(30.530427777778,-96.443216666667),L.latLng(30.530516666667,-96.447755555556),L.latLng(30.534394444444,-96.447652777778)])}); 

    
    
    map.addLayer(mapbox);

    var baseLayers = [
        {
            name: "Open Street Map",
            layer: osm_map
        },
        {
            name: "Satellie Map",
            layer: mapbox
        },
    ];

    var overLayers = [
        {
    group: 'test4',
    layers: [
        {
            name: '11/10/2020',
active: 'true',
            layer: layer_bigfgiletest4
        },
    ]
},

    ];

    var panelLayers = new L.Control.PanelLayers(baseLayers, overLayers, {collapsibleGroups: true});
    map.addControl(panelLayers);
    
</script>

</body>
</html>

Best answer

Looks like you are trying to visualize a high resolution picture covering a quite small area, given the bounds of your custom Tile Layer:

var layer_bigfgiletest4 = L.tileLayer('<url>/{z}/{x}/{y}.png', {
  bounds: L.latLngBounds([
    L.latLng(30.534394444444, -96.447652777778),
    L.latLng(30.534305555556, -96.443116666667),
    L.latLng(30.530427777778, -96.443216666667),
    L.latLng(30.530516666667, -96.447755555556),
    L.latLng(30.534394444444, -96.447652777778)
  ])
}); 

But because your initial map view position is way off and already highly zoomed in, you may not be able to see it even after panning around quite a bit.

var map = L.map('map', {
        center: L.latLng([27.7823,-97.5606]), // way off layer bounds
        zoom: 19, // highly zoomed in
        minZoom: 17,
        maxZoom: 25
});

You can re-adjust your map position when your Layer is added:

map.on("layeradd", function (event) {
  if (event.target === layer_bigfgiletest4) {
    map.fitBounds(/* same bounds */);
  }
});