计算当前位置的经度和纬度

时间:2011-05-04 14:04:09

标签: javascript python django view

我有特定地方的硬编码地址,但我想计算当前位置的经度和纬度(使用jquery或python脚本)。这是我目前的Django观点:

def maps(request):
    school = School.objects.get(id=1)
    dictte={'latitude':school.latitute,'longitude':school.longitude}
    print dictte
    print dictte.keys()
    print dictte['latitude'],'-----'
    school_latitute = float(dictte['latitude'])
    print school_latitute,'raj'
    print dictte['longitude'],'===='
    school_longtitude = float(dictte['longitude'])
    print school
    api_key="aa"
    gmaps = GoogleMaps(api_key)
    address = 'Veerannapalya,Bangalore,Karnataka, India - 560043'
    lat, lng = gmaps.address_to_latlng(address)
    print lat, lng

    if lat == school_latitute and lng == school_longtitude:

        schoo = {'Name of the school':school.name, 'address':school.address.address}
        strf= str(schoo)
        print strf

        return HttpResponse(simplejson.dumps(strf),content_type = 'application/json; charset=utf8')
    else:
        print 'nothing'    
    return render_to_response('staff.html',{'lat':lat,'lng':lng},context_instance=RequestContext(request))

如您所见,该地址目前在行中已经过硬编码:

address = 'Veerannapalya,Bangalore,Karnataka, India - 560043'

然后,从中,我获得纬度/经度。我想要做的是在浏览器中获取用户的当前位置,然后使用此纬度/经度。

1 个答案:

答案 0 :(得分:2)

您可以使用W3 geolocation API在JavaScript中执行此客户端。

navigator.geolocation.getCurrentPosition(
  function(pos){
    var lat = pos.coords.latitude;
    var long = pos.coords.longitude;
    // send coordinates to server, or display on map, if you wish
  },
  function(){
    /* Handler if location could not be found */
  }
);

它还不是官方规范,但它适用于大多数PC浏览器和某些手机浏览器。这是devices where it does work的列表。