網頁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.pswp.cn/news/389432.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389432.shtml
英文地址,請注明出處:http://en.pswp.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;先切換…