网页JS获取当前地理位置(省市区)

网页JS获取当前地理位置(省市区)

一、总结

一句话总结:ip查询接口

 

二、网页JS获取当前地理位置(省市区)

  眼看2014又要过去了,翻翻今年的文章好像没有写几篇,忙真的或许已经不能成为借口了,在忙时间还是有的,就像海绵里的水挤挤总会有滴。真真的原因是没有学习过什么新的技术,工作过程中遇到的问题也不是非常难并且自己认为是没有什么可以记录分享的,大部分都是温习以前的技术,现在已经专门负责前端技术,发现这边的水还是非常深,技术太多了,想学真的一时半会儿学不完。

  今年的项目开发中,初步接触了移动端WEB开发,也就边学习HTML5边开发,主要使用了JQuery Mobile技术,发现这个不适合做互联网产品,大部分样式都需要重写,只用了部分功能。手机端WEB开发过程中第一次接触了定位功能,通过各大搜索引擎发现手机端定位都是通过浏览器的定位,而用在PC端浏览器第一次会弹出提示“是否开启定位功能”,Boss看到这个提示,却觉得对用户的体验效果不好,不好那我换一种方式实现不就好了,这又不是多大的事,而Boss的脸色就大变,就说:不应该有这样的体验。我们这样做不都是为了赶时间,能够尽快将新功能发布嘛。

  1.手机WEB定位方法:

var getLocation = function (successFunc, errorFunc) { //successFunc获取定位成功回调函数,errorFunc获取定位失败回调//首先设置默认城市var defCity = {id: '000001',name: '北京市',date: curDateTime()//获取当前时间方法};//默认城市$.cookie('VPIAO_MOBILE_DEFAULTCITY', JSON.stringify(defCity), { expires: 1, path: '/' });if (navigator.geolocation) {navigator.geolocation.getCurrentPosition(function (position) {var lat = position.coords.latitude;var lon = position.coords.longitude;//var map = new BMap.Map("container");   // 创建Map实例var point = new BMap.Point(lon, lat); // 创建点坐标var gc = new BMap.Geocoder();gc.getLocation(point, function (rs) {var addComp = rs.addressComponents;var curCity = {id: '',name: addComp.province,date: curDateTime()};//当前定位城市$.cookie('VPIAO_MOBILE_CURRENTCITY', JSON.stringify(curCity), { expires: 7, path: '/' });//alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street);if (successFunc != undefined)successFunc(addComp);});},function (error) {switch (error.code) {case 1:alert("位置服务被拒绝。");break;case 2:alert("暂时获取不到位置信息。");break;case 3:alert("获取位置信息超时。");break;default:alert("未知错误。");break;}var curCity = {id: '000001',name: '北京市',date: curDateTime()};//默认城市$.cookie('VPIAO_MOBILE_DEFAULTCITY', JSON.stringify(curCity), { expires: 1, path: '/' });if (errorFunc != undefined)errorFunc(error);}, { timeout: 5000, enableHighAccuracy: true });} else {alert("你的浏览器不支持获取地理位置信息。");if (errorFunc != undefined)errorFunc("你的浏览器不支持获取地理位置信息。");}
};
var showPosition = function (position) {var lat = position.coords.latitude;var lon = position.coords.longitude;//var map = new BMap.Map("container");   // 创建Map实例var point = new BMap.Point(lon, lat); // 创建点坐标var gc = new BMap.Geocoder();gc.getLocation(point, function (rs) {var addComp = rs.addressComponents;var curCity = {id: '',name: addComp.province,date: curDateTime()};//当前定位城市$.cookie('VPIAO_MOBILE_CURRENTCITY', JSON.stringify(curCity), { expires: 7, path: '/' });//alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street);});
};
var showPositionError = function (error) {switch (error.code) {case 1:alert("位置服务被拒绝。");break;case 2:alert("暂时获取不到位置信息。");break;case 3:alert("获取位置信息超时。");break;default:alert("未知错误。");break;}var curCity = {id: '000001',name: '北京市',date: curDateTime()};//默认城市$.cookie('VPIAO_MOBILE_DEFAULTCITY', JSON.stringify(curCity), { expires: 1, path: '/' });
};

前提要引入百度API:<script src="http://api.map.baidu.com/api?v=1.4" type="text/javascript"></script>

  2.PC端通过IP实现方法:

  采用腾讯提供的接口,这个目前已经不能使用了  

<script type="text/javascript" src="http://fw.qq.com/ipaddress"></script>
<script type="text/javascript">document.write(IPData[0]);    //显示IP地址document.write(IPData[2]);    //显示省document.write(IPData[3]);    //显示市
</script>

  采用新浪接口: http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js 

  多地域测试方法:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=127.0.0.1

<script type="text/javascript">$.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function(_result) {if (remote_ip_info.ret == '1') {alert('国家:' + remote_ip_info.country + '<BR>省:' + remote_ip_info.province + '<BR>市:' + remote_ip_info.city + '<BR>区:' + remote_ip_info.district + '<BR>ISP:' + remote_ip_info.isp + '<BR>类型:' + remote_ip_info.type + '<BR>其他:' + remote_ip_info.desc);} else {alert('没有找到匹配的IP地址信息!');}});
</script>

  网易有道IP地址接口(这个有待测试)

  http://www.youdao.com/smartresult-xml/search.s?type=ip&q=IP地址

     淘宝请求接口(GET)

<script>
var ip = "124.127.108.133";var url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;$.getJSON(url, function (json) {var myprovince2 = json.data.area;var mycity2 = json.data.region;alert("您所在的城市是:" + myprovince2 + mycity2);});
</script>

  太平洋IP地址库API接口

  http://whois.pconline.com.cn/?ip=[ip地址字符串]

  另外:还有google、搜狐等提供对应的接口,大家可以自己试一试。

  搜狐IP地址查询接口(默认GBK):http://pv.sohu.com/cityjson

     搜狐IP地址查询接口(可设置编码):http://pv.sohu.com/cityjson?ie=utf-8

     搜狐另外的IP地址查询接口:http://txt.go.sohu.com/ip/soip

 

  3.获取客户端IP方法

<script>
var url = 'http://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_=' + Math.random();$.getJSON(url, function(data) {alert(data.Ip);});
</script>

  

  今天就写到这吧,还有好多工作需要去完成,等有时间了可以试试其它接口。欢迎大家来拍砖,提供更好的方法。

 

 

 

 

转载于:https://www.cnblogs.com/Renyi-Fan/p/9191950.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/389432.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

大熊猫卸妆后_您不应错过的6大熊猫行动

大熊猫卸妆后数据科学 (Data Science) Pandas is used mainly for reading, cleaning, and extracting insights from data. We will see an advanced use of Pandas which are very important to a Data Scientist. These operations are used to analyze data and manipulate…

数据eda_关于分类和有序数据的EDA

数据eda数据科学和机器学习统计 (STATISTICS FOR DATA SCIENCE AND MACHINE LEARNING) Categorical variables are the ones where the possible values are provided as a set of options, it can be pre-defined or open. An example can be the gender of a person. In the …

PyTorch官方教程中文版:PYTORCH之60MIN入门教程代码学习

Pytorch入门 import torch""" 构建非初始化的矩阵 """x torch.empty(5,3) #print(x)""" 构建随机初始化矩阵 """x torch.rand(5,3)""" 构造一个矩阵全为 0&#xff0c;而且数据类型是 long &qu…

Flexbox 最简单的表单

弹性布局(Flexbox)逐渐流行&#xff0c;越来越多的人开始使用&#xff0c;因为它写Css布局真是太简单了一一、<form>元素表单使用<form>元素<form></form>复制代码上面是一个空的表单&#xff0c;根据HTML标准&#xff0c;它是一个块级元素&#xff0c…

CSS中的盒子模型

一.为什么使用CSS 1.有效的传递页面信息 2.使用CSS美化过的页面文本&#xff0c;使页面漂亮、美观&#xff0c;吸引用户 3.可以很好的突出页面的主题内容&#xff0c;使用户第一眼可以看到页面主要内容 4.具有良好的用户体验 二.字体样式属性 1.font-family:英…

jdk重启后步行_向后介绍步行以一种新颖的方式来预测未来

jdk重启后步行“永远不要做出预测&#xff0c;尤其是关于未来的预测。” (KK Steincke) (“Never Make Predictions, Especially About the Future.” (K. K. Steincke)) Does this picture portray a horse or a car? 这张照片描绘的是马还是汽车&#xff1f; How likely is …

PyTorch官方教程中文版:入门强化教程代码学习

PyTorch之数据加载和处理 from __future__ import print_function, division import os import torch import pandas as pd #用于更容易地进行csv解析 from skimage import io, transform #用于图像的IO和变换 import numpy as np import matplotlib.pyplot a…

css3-2 CSS3选择器和文本字体样式

css3-2 CSS3选择器和文本字体样式 一、总结 一句话总结&#xff1a;是要记下来的&#xff0c;记下来可以省很多事。 1、css的基本选择器中的:first-letter和:first-line是什么意思&#xff1f; :first-letter选择第一个单词&#xff0c;:first-line选择第一行 2、css的伪类选…

mongodb仲裁者_真理的仲裁者

mongodb仲裁者Coming out of college with a background in mathematics, I fell upward into the rapidly growing field of data analytics. It wasn’t until years later that I realized the incredible power that comes with the position. As Uncle Ben told Peter Par…

优化 回归_使用回归优化产品价格

优化 回归应用数据科学 (Applied data science) Price and quantity are two fundamental measures that determine the bottom line of every business, and setting the right price is one of the most important decisions a company can make. Under-pricing hurts the co…

Node.js——异步上传文件

前台代码 submit() {var file this.$refs.fileUpload.files[0];var formData new FormData();formData.append("file", file);formData.append("username", this.username);formData.append("password", this.password);axios.post("http…

用 JavaScript 的方式理解递归

原文地址 1. 递归是啥? 递归概念很简单&#xff0c;“自己调用自己”&#xff08;下面以函数为例&#xff09;。 在分析递归之前&#xff0c;需要了解下 JavaScript 中“压栈”&#xff08;call stack&#xff09; 概念。 2. 压栈与出栈 栈是什么&#xff1f;可以理解是在内存…

PyTorch官方教程中文版:Pytorch之图像篇

微调基于 torchvision 0.3的目标检测模型 """ 为数据集编写类 """ import os import numpy as np import torch from PIL import Imageclass PennFudanDataset(object):def __init__(self, root, transforms):self.root rootself.transforms …

大数据数据科学家常用面试题_进行数据科学工作面试

大数据数据科学家常用面试题During my time as a Data Scientist, I had the chance to interview my fair share of candidates for data-related roles. While doing this, I started noticing a pattern: some kinds of (simple) mistakes were overwhelmingly frequent amo…

scrapy模拟模拟点击_模拟大流行

scrapy模拟模拟点击复杂系统 (Complex Systems) In our daily life, we encounter many complex systems where individuals are interacting with each other such as the stock market or rush hour traffic. Finding appropriate models for these complex systems may give…

公司想申请网易企业电子邮箱,怎么样?

不论公司属于哪个行业&#xff0c;选择企业邮箱&#xff0c;交互界面友好度、稳定性、安全性都是选择邮箱所必须考虑的因素。网易企业邮箱邮箱方面已有21年的运营经验&#xff0c;是国内资历最高的电子邮箱&#xff0c;在各个方面都非常成熟完善。 从交互界面友好度来看&#x…

莫烦Matplotlib可视化第二章基本使用代码学习

基本用法 import matplotlib.pyplot as plt import numpy as np""" 2.1基本用法 """ # x np.linspace(-1,1,50) #[-1,1]50个点 # #y 2*x 1 # # y x**2 # plt.plot(x,y) #注意&#xff1a;x,y顺序不能反 # plt.show()"""…

vue.js python_使用Python和Vue.js自动化报告过程

vue.js pythonIf your organization does not have a data visualization solution like Tableau or PowerBI nor means to host a server to deploy open source solutions like Dash then you are probably stuck doing reports with Excel or exporting your notebooks.如果…

plsql中导入csvs_在命令行中使用sql分析csvs

plsql中导入csvsIf you are familiar with coding in SQL, there is a strong chance you do it in PgAdmin, MySQL, BigQuery, SQL Server, etc. But there are times you just want to use your SQL skills for quick analysis on a small/medium sized dataset.如果您熟悉SQ…

第十八篇 Linux环境下常用软件安装和使用指南

提醒&#xff1a;如果之后要安装virtualenvwrapper的话&#xff0c;可以直接跳到安装virtualenvwrapper的方法&#xff0c;而不需要先安装好virtualenv安装virtualenv和生成虚拟环境安装virtualenv&#xff1a;yum -y install python-virtualenv生成虚拟环境&#xff1a;先切换…