This time the effect is that as soon as the page is opened it automatically sends a request to the server to get the data and draw it to the page automatically

No more nonsense, follow the steps on the code:

Stomp Connection Part (JS)

 /** * set up the connection, I control the asynchronous processing all use setTimeout, suggest in order to code readable and maintainable, try to use the event listening * here lazy or use the broadcast mode, suggest using 1 to 1 communication */
		function setCon(getData){
				stompClient.connect({},function (frame){
				//console.log(" Server connection "+frame);
				setTimeout(2000);
				getData();
				});
	
		};
                
		// Automatically subscribe to message channels and interact
		// Subscribe to get messages
	 	// Start communication by sending a send after receiving a subscription
		function getData(){
			setTimeout(function(){
				stompClient.subscribe("/system/china_motor".function(mes){
	 		    	dataLog = JSON.parse(mes.body);
	 		    	// Process the resulting data
				temp = Object.keys(dataLog);
	 		    	arr=(Object.values(dataLog));
				arr = arr[0];
                                // Refresh data
				refreshData(arr,temp);
                                // Make sure the loop is complete before sending the request
                                stompClient.send("/app/china_motor", {},"iamready"); })},1000)
                        setTimeout(function(){stompClient.send("/app/china_motor", {},"iamready")},1000);
		};
                
		// Refresh the path tag in traversal form
		function refreshData(arr,temp){
			svg.selectAll("path").each(function (d,i) {
		            if (arr.includes(i)) {
		                d3.select(this).attr("stroke",temp); }})}// Link closed
	function sendGoodBye(){
		stompClient.send("/app/china_motor", {},"iamfinished");
	}
	function disconnect(){
	 	stompClient.disconnect();
	 }

Copy the code

JS client part

    	<svg class ="china"></svg>
	<script>
        // Set the size
    const svgWidth = 1200;
    const svgHeight =900;
    const padding = 1;
    
    const svg = d3.select(".china")
        .attr("height", svgHeight)
        .attr("width", svgWidth);

		/* * Create a geographic projection *. Center sets the location of the projection center *. Scale sets the scaling factor */
	const x0 = padding;
	const y0 = padding;
	const x1 = svgWidth - padding * 2;
	const y1 = svgHeight - padding * 2;
	const projection = d3.geoMercator().fitExtent(
			[
				[x0,y0],
				[x1,y1],
			],china
		 );
		// Center alignment can be modified to improve speed. -
		// Create the path generator path
		var path = d3.geoPath().projection(projection);

		 // Render the map
	const mapPath = svg.selectAll("path");
        // Load the data, I did not give the data source here, you can see my previous blog
		  mapPath.data(china.features)
			.join('path')
			.attr('d', path)
			//.attr('id',china.features.properties.valueof(osm_id))
			.attr("stroke-width".2)
			.attr("stroke"."#00cc00")
			.attr("fill"."# 000000");
			
	// Set up a connection and start communicating
	var linstener = "/system/china_motor"
	socket = new SockJS('/stomp');
	stompClient = Stomp.over(socket);
	var data;
	setCon(getData);
	</script>

<script>
// Close the link when exiting the page or changing the page to prevent occupation
 window.onbeforeunload = function(e) {
	sendGoodBye();
	disconnect();
	} 
</script>
    
Copy the code

Server part:

// The database is not connected yet, use random number test.
    	@MessageMapping("/china_motor")
	@SendTo("/system/china_motor")
	public void sentMotor(@Payload String name) throws InterruptedException {
		int size = 0;
		int a = 0;
		int max = 248306;
		int big = 0;
		String color;
		System.out.println(name);
		trafficStream ts = new trafficStream();
		if(name.equals("iamready")) {
                // Generate random number tests
			Random rd = new Random();
			a = rd.nextInt(3);
			switch(a) {
			case 0: 
				color="#ff0000";
				size = 1000;
				break;
			case 1:
				color="#ffff00";
				size = 10000;
				break;
			case 2:
				color="##00cc00";
				size = 10000;
				break;
			default:
				color = "##00cc00";
				size = 10000;
				;
			}
			int[] sort = new int [size];
			sort = ts.randomArray(0, max, size);
			Map<String,int[]> msg = new HashMap<String, int[] > (); msg.put(color, sort); Thread.sleep(6000);
			peopelFlow.convertAndSend("/system/china_motor",msg);
		}
                // Handle the event
		else if(name.equals("iamfinished")) {
				System.out.println("connect finished"); peopelFlow.setSendTimeout(j); }}Copy the code

StompConfig parts:

    public static final String BROKER_CHINA = "/system/china_motor";
	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
			// Used to specify which addresses clients can subscribe to
			config.enableSimpleBroker(BROKER_CHINA);
			// The server address prefix used by the client to send messages
			config.setApplicationDestinationPrefixes("/app");
			// the server sends the prefix /system/ MSG to the client to broadcast /user/system/ MSG to the client
			config.setUserDestinationPrefix("/user");
		}
	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		//SockJS is used to define connection nodes
		registry.addEndpoint("/stomp")//.setHandshakeHandler(new CustomHandler())//.setAllowedOrigins("*")
                        .withSockJS();		
	}
	// Configure the number of threads (pool) to prevent wrong order
	@Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.taskExecutor().corePoolSize(1).maxPoolSize(1);
    }

Copy the code

Effect display:

Zoom in ~

Depending on the amount of data set and the random probability, the yellow quickly fills up

Since it’s random data, it looks a bit fake, but it’s real time updates based on server-side data.

Background data can also be seen:

Main problems:

  1. The js mentioned above should use event listeners to handle asynchronous events

  2. The algorithm is not optimized and takes up a lot of computing and memory resources

  3. A large amount of data slows web page loading and STOMP packet processing

  4. Incomplete data can be added to ‘motor_link’ in OSM_Roads for complete data

There are plenty of other minor flaws.

I’ll optimize it when I feel like it. –

We look forward to your comments and suggestions.

1. For OSM data processing and visualization, please refer to my article:(I am happy drain tag ^ _ ^)

2. You can read my article about STOMp:(I am another happy drain tag ^ _ ^)