search
HomeBackend DevelopmentPHP TutorialPHP+Mysql+jQuery中国地图区域数据统计实例讲解_php实例

今天我要给大家介绍在实际应用中,如何把数据载入到地图中。本文结合实例,使用PHP+Mysql+jQuery实现中国地图各省份数据统计效果。


本例以统计某产品在各省份的活跃用户数为背景,数据来源于mysql数据库,根据各省份的活跃用户数,分成不同等级,并以不同的背景色显示各省份的活跃程度,符合实际应用需求。

HTML

首先在head部分载入raphael.js库文件和chinamapPath.js路径信息文件。

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript" src="raphael.js"></script> 
<script type="text/javascript" src="chinamapPath.js"></script>

然后在body中需要放置地图的位置放置div#map。

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

PHP

我们准备一张mysql表名为mapdata,这张表存储的是产品在各个省份的活跃用户数据。我们使用PHP读取mysql表中的数据,并将读取的数据以json格式输出,并将PHP文件命名为json.php。

$host="localhost";//主机 
$db_user="root";//数据库用户名 
$db_pass="";//密码 
$db_name="demo";//数据库名称 
 
$link=mysql_connect($host,$db_user,$db_pass);//连接数据库 
mysql_select_db($db_name,$link); 
mysql_query("SET names UTF8"); 
 
$sql = "select active from mapdata order by id asc";//查询 
$query = mysql_query($sql); 
 
while($row=mysql_fetch_array($query)){ 
  $arr[] = $row['active']; 
} 
echo json_encode($arr);//JSON格式 
mysql_close($link);//关闭连接

值得注意的是,我们要把mapdata表中各省份的排序与chinamapPath.js文件中的各省份顺序一致,这样才能保证读取的数据能和地图中的省份对应上。

jQuery

首先我们使用jquery的get()方法获取json数据。

$(function(){ 
  $.get("json.php",function(json){ 
    ... 
  }); 
});

获取到json数据后,我们先要将json数据转换为数组,然后我们遍历整个数组,根据json数据中各省份活跃用户数的多少,我们作一个等级区分,这里我将等级分为0-5六个等级,活跃用户数越大背景颜色越深,这样在地图上显示就会一目了然的看出不同省份的数据等级程度。

请看整理好的代码:

$(function(){ 
 $.get("json.php",function(json){//获取数据 
 var data = string2Array(json);//转换数组 
  
 var flag; 
 var arr = new Array();//定义新数组,对应等级 
 for(var i=0;i<data.length;i++){ 
  var d = data[i]; 
  if(d<100){ 
   flag = 0; 
  }else if(d>=100 && d<500){ 
   flag = 1; 
  }else if(d>=500 && d<2000){ 
   flag = 2; 
  }else if(d>=2000 && d<5000){ 
   flag = 3; 
  }else if(d>=5000 && d<10000){ 
   flag = 4; 
  }else{ 
   flag = 5; 
  } 
  arr.push(flag); 
 } 
 //定义颜色 
 var colors = ["#d7eef8","#97d6f5","#3fbeef","#00a2e9","#0084be","#005c86"]; 
  
 //调用绘制地图方法 
 var R = Raphael("map", 600, 500); 
 paintMap(R); 
  
 var textAttr = { 
  "fill": "#000", 
  "font-size": "12px", 
  "cursor": "pointer" 
 }; 
    
 var i=0; 
 for (var state in china) { 
  china[state]['path'].color = Raphael.getColor(0.9); 
  (function (st, state) { 
    
   //获取当前图形的中心坐标 
   var xx = st.getBBox().x + (st.getBBox().width / 2); 
   var yy = st.getBBox().y + (st.getBBox().height / 2); 
    
   //修改部分地图文字偏移坐标 
   switch (china[state]['name']) { 
    case "江苏": 
     xx += 5; 
     yy -= 10; 
     break; 
    case "河北": 
     xx -= 10; 
     yy += 20; 
     break; 
    case "天津": 
     xx += 10; 
     yy += 10; 
     break; 
    case "上海": 
     xx += 10; 
     break; 
    case "广东": 
     yy -= 10; 
     break; 
    case "澳门": 
     yy += 10; 
     break; 
    case "香港": 
     xx += 20; 
     yy += 5; 
     break; 
    case "甘肃": 
     xx -= 40; 
     yy -= 30; 
     break; 
    case "陕西": 
     xx += 5; 
     yy += 10; 
     break; 
    case "内蒙古": 
     xx -= 15; 
     yy += 65; 
     break; 
    default: 
   } 
   //写入文字 
   china[state]['text'] = R.text(xx, yy, china[state]['name']).attr(textAttr); 
    
   var fillcolor = colors[arr[i]];//获取对应的颜色 
    
   st.attr({fill:fillcolor});//填充背景色 
    
   st[0].onmouseover = function () { 
    st.animate({fill: "#fdd", stroke: "#eee"}, 500); 
    china[state]['text'].toFront(); 
    R.safari(); 
   }; 
   st[0].onmouseout = function () { 
    st.animate({fill: fillcolor, stroke: "#eee"}, 500); 
    china[state]['text'].toFront(); 
    R.safari(); 
   }; 
      
   })(china[state]['path'], state); 
   i++; 
 } 
 }); 
});

上述代码中,使用var fillcolor = colors[arr[i]];获取对应等级的颜色值,然后通过st.attr({fill:fillcolor});将颜色填充到对应的省份区块中。此外string2Array()函数是将字符串转换为数组。

function string2Array(string) { 
  eval("var result = " + decodeURI(string)); 
  return result; 
}

通过以上步骤,我们就可以看到一个不同省份不同背景色的中国地图,根据不同颜色可以区分省份之间的活跃用户数差异程度,达到预期目标,小伙伴们希望这篇文章对大家的学习有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.