Showing posts with label map. Show all posts
Showing posts with label map. Show all posts

Saturday, December 31, 2022

MapBox Implementation of Map: How to plot multiple points on MapBox using a for each statement - multiple points with exactly the same location using MapBox

Below is code example of plot multiple points on MapBox:
<div id='map' class="map"></div>
<script type="text/javascript">
    mapboxgl.accessToken = "pk.your-access-token";

    const map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v9',
        center: [6.055737, 46.233226],
        zoom: 13,
        scrollZoom: true
    });
    map.on('load', function(){
        console.log('map loaded');
        const locations = [
            [6.055737, 46.233226],
            [6.0510, 46.2278],
            [6.0471, 46.23336],
            [6.0371, 46.23336]
        ];
        locations.forEach(function(coords) {
            new mapboxgl.Marker().setLngLat(coords).addTo(map);
        });
    });
</script>
Output is as:

Friday, December 30, 2022

Free Map Integration - Leaflet.js with OpenStreetMap tiles - Display multiple point locations as map markers - Plot multiple points on Map view - Display multiple point locations as map markers

Here is the documantation https://leafletjs.com/examples/quick-start/
Code snippet (Download full code from here):
<script src="//code.jquery.com/jquery-3.6.1.min.js"></script>
<link rel="stylesheet" href="leaflet.css" />
<script src="leaflet.js"></script>

<!-- https://leafletjs.com -->

<div id="leaflet-js-map"></div>
<div>
    <button id="moveToPoint">Move to specific point</button>
</div>
<script type="text/javascript">
    const map = L.map('leaflet-js-map').setView([46.241226, 6.051737], 14);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        minZoom: 0,
        maxZoom: 18,
        attribution: 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'
    }).addTo(map);
    const leafletMarkers = L.layerGroup([
        new L.marker([46.233226, 6.055737]),
        new L.marker([46.2278, 6.0510]),
        new L.marker([46.23336, 6.0471])
    ]);
    leafletMarkers.addTo(map);

    var LeafIcon = L.Icon.extend({
        options: {
            shadowUrl: 'images/leaf-shadow.png',
            iconSize:     [38, 95],
            shadowSize:   [50, 64],
            iconAnchor:   [22, 94],
            shadowAnchor: [4, 62],
            popupAnchor:  [-3, -76]
        }
    });
    var greenIcon = new LeafIcon({iconUrl: 'images/leaf-green.png'}),
        redIcon = new LeafIcon({iconUrl: 'images/leaf-red.png'}),
        orangeIcon = new LeafIcon({iconUrl: 'images/leaf-orange.png'});
    L.icon = function (options) {
        return new L.Icon(options);
    };
    L.marker([46.234226, 6.055737], {icon: greenIcon}).addTo(map).bindPopup("I am a green leaf.");
    L.marker([46.237226, 6.052737], {icon: redIcon}).addTo(map).bindPopup("I am a red leaf.");
    L.marker([46.240226, 6.065737], {icon: orangeIcon}).addTo(map).bindPopup("I am an orange leaf.");


    [{T: 46.249226, N: 6.056937, D: '1'}, {T: 46.250226, N: 6.066937, D: '2'}].forEach(function (t) {
        const el = document.createElement('div');
        L.marker([t.T, t.N]).addTo(map).on("click", function () {
            console.log(this);
            var popup = L.popup()
                .setLatLng(this._latlng)
                .setContent('<p>Hello world!<br />This is a nice popup-' + t.D + '</p>')
                .openOn(map);
        })
    });

    $("#moveToPoint").on("click", function () {
        map.flyTo(L.latLng(46.249226, 6.056937), 15);

        const popUps = document.getElementsByClassName('leaflet-popup');
        if (popUps[0]) popUps[0].remove();

        L.popup()
            .setLatLng(L.latLng(46.250226, 6.056937))
            .setContent('<p>Hello world!<br />This is a nice popup-Self</p>')
            .openOn(map);
    });
</script>
<style type="text/css">
    #leaflet-js-map {
        width: 100%;
        height: 500px;
    }
</style>
Output is as below:

Saturday, December 17, 2016

How to convert Map / Object to Bytes and save to internal storage and read back

package com.pkm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author PRITOM
 */
public class MapObjectToByteArrayAndSaveToFile {
    public static void main(String[] args) throws Exception {
        Map<Integer, String> data = new HashMap<Integer, String>();
        data.put(1, "hello");
        data.put(2, "world");
        System.out.println(data.toString());
        store(data);
        data = (Map<Integer, String>) load();
        System.out.println(data.toString());
    }
    
    public static Object load() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("object.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        return objectInputStream.readObject();
    }
    
    public static void store(Object data) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("object.txt");
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(data);
        outputStream.close();
    }
}

Monday, May 5, 2014

Convert Map, HashMap or List/ArrayList to XML and reverse

HashMapToStringXml.java

package pritom;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pritom on 5/05/14.
 */
public class HashMapToStringXml {
    public static void main(String[] args) {
        Map<Object, Object> hashMap = new HashMap<Object, Object>();
        hashMap.put("firstName", "Pritom");
        hashMap.put("lastName", "Kumar");

        Map<Object, Object> secondMap = new HashMap<Object, Object>();
        secondMap.put("timeIn", "8:00");
        secondMap.put("timeOut", "5:00");
        hashMap.put("timing", secondMap);

        List<Object> list = new ArrayList<Object>();
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(secondMap);
        hashMap.put("contents", list);

        /* Map to XML and reverse */
        String mapToString = objectToString(hashMap);
        Map parsedMap = (Map) stringToObject(mapToString);
        System.out.println("Map to XML: \n" + mapToString + "\nXML to map:\n" + parsedMap);

        /* List to XML and reverse */
        String listToString = objectToString(list);
        List parsedList = (List) stringToObject(listToString);
        System.out.println("List to XML: \n" + listToString + "\nXML to list:\n" + parsedList);
    }

    public static String objectToString(Object hashMap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XMLEncoder xmlEncoder = new XMLEncoder(bos);
        xmlEncoder.writeObject(hashMap);
        xmlEncoder.close();
        return bos.toString();
    }

    public static Object stringToObject(String string) {
        XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream(string.getBytes()));
        return xmlDecoder.readObject();
    }
}

Output

Map to XML: 
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_45" class="java.beans.XMLDecoder">
 <object class="java.util.HashMap">
  <void method="put">
   <string>lastName</string>
   <string>Kumar</string>
  </void>
  <void method="put">
   <string>contents</string>
   <object class="java.util.ArrayList">
    <void method="add">
     <int>20</int>
    </void>
    <void method="add">
     <int>30</int>
    </void>
    <void method="add">
     <int>40</int>
    </void>
    <void method="add">
     <object class="java.util.HashMap" id="HashMap0">
      <void method="put">
       <string>timeOut</string>
       <string>5:00</string>
      </void>
      <void method="put">
       <string>timeIn</string>
       <string>8:00</string>
      </void>
     </object>
    </void>
   </object>
  </void>
  <void method="put">
   <string>timing</string>
   <object idref="HashMap0"/>
  </void>
  <void method="put">
   <string>firstName</string>
   <string>Pritom</string>
  </void>
 </object>
</java>

XML to map:
{
    lastName=Kumar, 
    contents=[
        20, 
        30, 
        40, 
        {
            timeOut=5:00, 
            timeIn=8:00
        }
    ], 
    firstName=Pritom, 
    timing={
        timeOut=5:00, 
        timeIn=8:00
    }
}



List to XML: 
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_45" class="java.beans.XMLDecoder">
 <object class="java.util.ArrayList">
  <void method="add">
   <int>20</int>
  </void>
  <void method="add">
   <int>30</int>
  </void>
  <void method="add">
   <int>40</int>
  </void>
  <void method="add">
   <object class="java.util.HashMap">
    <void method="put">
     <string>timeOut</string>
     <string>5:00</string>
    </void>
    <void method="put">
     <string>timeIn</string>
     <string>8:00</string>
    </void>
   </object>
  </void>
 </object>
</java>

XML to list:
[20, 30, 40, {timeOut=5:00, timeIn=8:00}]

Friday, May 2, 2014

Iterate over each Entry in HashMap in Java Or loop Map to remove Entries

Example Class: HashMapIterator.java

package com.pkm.annotation;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author Pritom
 */
public class HashMapIterator {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("key1", "Value 1");
        map.put("key2", "Value 2");
        map.put("key3", "Value 3");
        map.put("key4", "Value 4");
        map.put("key5", "Value 5");
        
        /* Using Iterator */
        System.out.println("Using Iterator");
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) iterator.next();
            System.out.println("Key: " + mapEntry.getKey() + ", Value: " + 
                    mapEntry.getValue());
            if(mapEntry.getKey().toString().equals("key3")) {
                /* Removing without ConcurrentModificationException */
                iterator.remove(); 
            }
        }
        
        /* Using Direct Entry Set */
        System.out.println("\nUsing Direct Entry Set");
        for (Object entry : map.entrySet()) {
            Map.Entry mapEntry = (Map.Entry) entry;
            System.out.println("Key : " + mapEntry.getKey() + ", Value : "
                    + mapEntry.getValue());
        }
        
        /* Using Direct Key Set */
        System.out.println("\nUsing Direct Key Set");
        for (Object entry : map.keySet()) {
            System.out.println("Key : " + entry + ", Value : "
                    + map.get(entry));
        }
    }
}

Example Output:

Using Iterator
Key: key4, Value: Value 4
Key: key3, Value: Value 3
Key: key5, Value: Value 5
Key: key2, Value: Value 2
Key: key1, Value: Value 1

Using Direct Entry Set
Key : key4, Value : Value 4
Key : key5, Value : Value 5
Key : key2, Value : Value 2
Key : key1, Value : Value 1

Using Direct Key Set
Key : key4, Value : Value 4
Key : key5, Value : Value 5
Key : key2, Value : Value 2
Key : key1, Value : Value 1

Tuesday, December 3, 2013

Avoid ConcurrentModificationException when using an Java Iterator

Lets explore this scenario with the following example:
First see two methods and then see last two methods.
For first two methods, used simple arraylist and hashmap, so concurrent exception occurs.
But for the later two methods, used copy on write arraylist and concurrent hashmap, so no problem with the last two methods.

package pritom;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: pritom
 * Date: 3/12/13
 * Time: 4:04 PM
 * To change this template use File | Settings | File Templates.
 */
public class ConcurrentModification {
    public static void main(String[] args) {
        ConcurrentModification.concurrentModificationList();
        ConcurrentModification.concurrentModificationHashMap();
        ConcurrentModification.concurrentModificationConcurrentList();
        ConcurrentModification.concurrentModificationConcurrentHashMap();
    }

    private static void concurrentModificationList() {
        try {
            List<String> myDataList = new ArrayList<String>();
            myDataList.add("1");
            myDataList.add("2");
            myDataList.add("3");
            myDataList.add("4");

            System.out.println("Deleting from List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                if(myObject.equalsIgnoreCase("2") || myObject.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + myObject);
                    myDataList.remove(myObject);
                } else {
                    System.out.println("Not deleting: " + myObject);
                }
            }

            System.out.println("After deleting from List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                System.out.println("Remaining: " + myObject);
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from List error: " + ex.toString() + " *****");
        }
    }

    private static void concurrentModificationHashMap() {
        try {
            Map<String, String> myDataList = new HashMap<String, String>();
            myDataList.put("0", "00");
            myDataList.put("1", "11");
            myDataList.put("2", "22");
            myDataList.put("3", "33");

            System.out.println("\n\nDeleting from Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                if(key.equalsIgnoreCase("2") || key.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + key + " = " + myDataList.get(key));
                    myDataList.remove(key);
                } else {
                    System.out.println("Not deleting: " + key + " = " + myDataList.get(key));
                }
            }

            System.out.println("After deleting from Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                System.out.println("Remaining: " + key + " = " + myDataList.get(key));
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Map error: " + ex.toString() + " *****\n\n");
        }
    }

    private static void concurrentModificationConcurrentList() {
        try {
            List<String> myDataList = new CopyOnWriteArrayList<String>();
            myDataList.add("1");
            myDataList.add("2");
            myDataList.add("3");
            myDataList.add("4");

            System.out.println("\n\nDeleting from Concurrent List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                if(myObject.equalsIgnoreCase("2") || myObject.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + myObject);
                    myDataList.remove(myObject);
                    myDataList.add("55");
                } else {
                    System.out.println("Not deleting: " + myObject);
                }
            }

            System.out.println("After deleting from Concurrent List: ");
            for (Iterator it = myDataList.iterator(); it.hasNext();) {
                String myObject = (String) it.next();
                System.out.println("Remaining: " + myObject);
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Concurrent List error: " + ex.toString() + " *****");
        }
    }

    private static void concurrentModificationConcurrentHashMap() {
        try {
            Map<String, String> myDataList = new ConcurrentHashMap<String, String>();
            myDataList.put("1", "11");
            myDataList.put("2", "22");
            myDataList.put("3", "33");
            myDataList.put("4", "44");

            System.out.println("\n\nDeleting from Concurrent Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                if(key.equalsIgnoreCase("2") || key.equalsIgnoreCase("4")) {
                    System.out.println("Deleting: " + key + " = " + myDataList.get(key));
                    myDataList.remove(key);
                    System.out.println("Adding: 5 = 55");
                    myDataList.put("5", "55");
                } else {
                    System.out.println("Not deleting: " + key + " = " + myDataList.get(key));
                }
            }

            System.out.println("After deleting from Concurrent Map: ");
            for (Iterator it = myDataList.keySet().iterator(); it.hasNext();) {
                String key = (String) it.next();
                System.out.println("Remaining: " + key + " = " + myDataList.get(key));
            }
        } catch (Throwable ex) {
            System.out.println("***** Deleting from Concurrent Map error: " + ex.toString() + " *****\n\n");
        }
    }
}

And see the output


Deleting from List: 
Not deleting: 1
Deleting: 2
***** Deleting from List error: java.util.ConcurrentModificationException *****


Deleting from Map: 
Not deleting: 3 = 33
Deleting: 2 = 22
***** Deleting from Map error: java.util.ConcurrentModificationException *****




Deleting from Concurrent List: 
Not deleting: 1
Deleting: 2
Not deleting: 3
Deleting: 4
After deleting from Concurrent List: 
Remaining: 1
Remaining: 3
Remaining: 55
Remaining: 55


Deleting from Concurrent Map: 
Not deleting: 1 = 11
Not deleting: 3 = 33
Deleting: 4 = 44
Adding: 5 = 55
Deleting: 2 = 22
Adding: 5 = 55
After deleting from Concurrent Map: 
Remaining: 1 = 11
Remaining: 5 = 55
Remaining: 3 = 33

To Avoid ConcurrentModificationException in multi-threaded environment (first two methods):
1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.
2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.
3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

From the above example its clear that (last two methods):
1. Concurrent Collection classes can be modified avoiding ConcurrentModificationException.
2. In case of CopyOnWriteArrayList, iterator doesn’t accomodate the changes in the list and works on the original list.
3. In case of ConcurrentHashMap, the behavior is not always the same.