JavaScript HTML5 canvas to implement China map _javascript techniques in a drag province

Source: Internet
Author: User

The example of this article shares the HTML5 Canvas Province of China Map implementation method, for your reference, the specific contents are as follows

1. Data acquisition
Map needs provinces border coordinates, theoretically can use Baidu API every time to get data and drawings, but in order to increase efficiency, first of all coordinates are captured and stored in the database.
New Province Data Array

Copy Code code as follows:
var allzonedata = [{' name ': ' Liaoning Province ', ' been ': ' Yes ', ' id ': '},<span ' style= ' font-family:arial, Helvetica, Sans-serif; >{' name ': ' Jilin Province ', ' been ': ' Yes ', ' id ': ',......]; </span>

Polling the array, according to the province name request Baidu API get coordinate data, and the data in Ajax way to relax to PHP

var Mygeo = new Bmap.geocoder (); 
 
(function () {for 
 (var i = 0;i < allzonedata.length;i++) { 
  getallzone (allzonedata[i].name,allzonedata[i). been,allzonedata[i].id); 
 } 
) (); 
Name is the name of the province, been indicates whether it has been, the ID is unique identifier, CIR is the province circle number (there may be a province with two parts closed circle) 
function Getallzone (name,been,id) { 
 var data, temp; 
         
 var bdary = new Bmap.boundary (); 
 Bdary.get (name, function (RS) { 
  var count = rs.boundaries.length;  
  for (var j = 0; J < Count; J +) {      
   var ply = new Bmap.polygon (Rs.boundaries[j], {strokeweight:2, Strokecolor: "#ff00 "}); 
   data = Ply.getpath (); 
   $.ajax ({ 
    URL: "adddata.php", 
    Type: "POST", 
    data: {' data ':d ata, ' name ': Name, ' Cir ': J, ' been ': Been, ' ID ' : id}, 
    success:function (TXT) { 
     console.log (TXT); 
    }, 
    error:function () { 
     alert (') Error adding data! '); 
    } 
   });   
  }         
 });         
} 

After PHP gets the data, it parses the data and stores the data in a database that was built in advance.

<?php 
  Header ("content-type:text/html; Charset=utf-8 "); 
  $data = $_request[' data ']; 
  $name = $_request[' name ']; 
  $cir = $_request[' Cir ']; 
  $been = $_request[' been ']; 
  $id = $_request[' id ']; 
 
  $con = mysql_connect ("localhost", "...", "..."); 
  if (! $con) { 
    die (' Could not connect: '. Mysql_error ()); 
  } 
  mysql_select_db ("...", $con); 
  Mysql_set_charset (' UTF8 ', $con); 
 
  foreach ($data as $temp) { 
    $sql = INSERT INTO place (Id,name,lng,lat,cir,been) VALUES ('. $id. "', '". $name. "', '". $te mp[' LNG ']. "', '". $temp [' lat ']. "', '", $cir. "', '". $been. ""; 
    if (!mysql_query ($sql, $con)) { 
      die (' Error: '. mysql_error ()); 
    } 
  } 
 
  Mysql_close ($con); 
  Echo ' Success '; 
? > 

2. Draw map (base ground drawing on Mapcanvas layer)
polls the province array and requests the province's boundary coordinates in AJAX mode, and then the drawing

var drawmap = function (context,data,l,t) {//context for the layer where the drawing is drawn, L and T are relative positions, data is an array of boundary objects 
 if (Data.been = = ' yes ') { 
  Context.fillstyle = "green"; 
 } else{ 
  context.fillstyle = "Grey"; 
 } 
 Context.globalalpha = 0.8; 
 Context.beginpath (); 
 Cleft = (data.coordinate[0].lng-temp_left) * bigger + L; Temp_left and Temp_top are offset locations for maps. 
 Ctop = (temp_top-data.coordinate[0].lat) * bigger + t; Bigger is the magnification 
 
 context.moveto (cleft,ctop); 
           
 for (var j = 1;j < data.coordinate.length;j++) { 
  cleft = (data.coordinate[j].lng-temp_left) * bigger + L; 
  Ctop = (temp_top-data.coordinate[j].lat) * bigger + t; 
  Context.lineto (cleft,ctop); 
 } 
           
 Context.closepath (); 
 Context.stroke (); 
 Context.fill (); 
} 

3. Draw mobile lines (wired and mobile provinces are painted on the Movemapcanvas layer)
when you drag a province on a map, there are several lines connecting the moving provinces and the original provinces

var drawlinkline = function (data,l,t) {//here L and T represent the relative position of movement for 
 (var k = 0;k < data.coordinate.length;k++) { 
  if k % = = 0) { 
   movemapcontext.beginpath (); 
           
   According to the different moving distance, set the thickness of the line 
   linelength = math.sqrt (L * l + t * t)/; 
   LineLength = linelength >= 4.5? 4.5:linelength; 
   Movemapcontext.linewidth = 5-linelength; 
 
   Movemapcontext.strokestyle = "Rgba (0,120,60,0.4)"; 
   Cleft = (data.coordinate[k].lng-temp_left) * bigger; 
   Ctop = (temp_top-data.coordinate[k].lat) * bigger; 
   Movemapcontext.moveto (cleft,ctop); 
 
   Cleft = (data.coordinate[k].lng-temp_left) * bigger + L; 
   Ctop = (temp_top-data.coordinate[k].lat) * bigger + t; 
   Movemapcontext.lineto (cleft,ctop); 
   Movemapcontext.closepath (); 
   Movemapontext.stroke ();}} 
 

4. The event
Mouse press event: When clicked on the map, to do is to judge the location of the click, the position of information into latitude and longitude, and then through the Baidu API according to the latitude and longitude of the province to obtain the name.

$ (' #eventCanvas '). MouseDown (function (EV) { 
 //Get click Canvas coordinates 
 var mousex, Mousey; 
 if (Ev.layerx | | ev.layerx==0) { 
  mousex = Ev.layerx; 
  Mousey = Ev.layery; 
 } else if (Ev.offsetx | | ev.offsetx==0) { 
  mousex = ev.offsetx; 
  Mousey = ev.offsety; 
 } 
 
 Save click on the original coordinate value 
 tempx = mousex; 
 Tempy = Mousey; 
 
 Transformation of coordinates into latitude and longitude 
 mousex = Mousex/bigger + temp_left; 
 Mousey = Temp_top-mousey/bigger; 
 
 if (opts.dragall) { 
  draging = true; 
 } else{ 
  movemapcontext.clearrect (0, 0, 1100, 630); 
  Obtain the geographical location according to the latitude and longitude and obtain the boundary coordinates redraw line 
  mygeo.getlocation (New Bmap.point (MouseX, mousey), 
   function (result) { 
    Tempname = '; 
    Draging = true; 
    name = Result.addressComponents.province; 
    Tempname = name; 
    Pubfuns.drawmovelayerline (0,0);    
  }); 
 

Mouse movement Events: provinces where the data is obtained and the moving layer is redrawn in real time according to the clicked province name

$ (' #eventCanvas '). MouseMove (function (EV) { 
 var mousex, Mousey; 
 if (Ev.layerx | | ev.layerx==0) { 
  mousex = Ev.layerx; 
  Mousey = Ev.layery; 
 } else if (Ev.offsetx | | ev.offsetx==0) { 
  mousex = ev.offsetx; 
  Mousey = ev.offsety; 
 } 
 if (draging) { 
  if (opts.dragall) {<span style= "font-family:arial, Helvetica, Sans-serif;" >//Drag the entire map, there are problems, the map is drawing too slow </span> 
   mapcontext.clearrect (0, 0, 1100, 630); 
   for (var i = 0;i < allzonedata.length;i++) {for 
    (var j = 0;j < alldata[allzonedata[i].name].length;j++) {//allda TA is a variable that is put into memory the first time it reads data, and it contains all the data 
     Pubfuns.drawmap (MAPCONTEXT,ALLDATA[ALLZONEDATA[I].NAME][J],MOUSEX-TEMPX, mousey-tempy);}} 
   else{ 
    movemapcontext.clearrect (0, 0, 1100, 630); 
    Pubfuns.drawmovelayerline (MOUSEX-TEMPX, mousey-tempy); 
   }  
  } 
); 

Mouse Lift event: Set dragging as false,clear move layer.

$ (' #eventCanvas '). MouseUp (function (e) { 
 if (opts.dragall) {  
 }else{ 
  movemapcontext.clearrect (0, 0, 1100, 630); 
 } 
 Draging = false; 

Summary: The function, the principle is very simple, but can acquaint with the canvas some attributes and the method. The canvas layer can be overlapped so that different content can be drawn on different layers to facilitate maintenance and management.

The above is the entire content of this article, I hope to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.