simple_geolocation_provider.cc revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
1// Copyright 2014 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "chrome/browser/chromeos/geolocation/simple_geolocation_provider.h" 6 7#include <algorithm> 8#include <iterator> 9 10#include "base/bind.h" 11#include "base/time/time.h" 12#include "chrome/browser/chromeos/geolocation/geoposition.h" 13#include "net/url_request/url_request_context_getter.h" 14#include "url/gurl.h" 15 16namespace chromeos { 17 18namespace { 19const char kDefaultGeolocationProviderUrl[] = 20 "https://www.googleapis.com/geolocation/v1/geolocate?"; 21} // namespace 22 23SimpleGeolocationProvider::SimpleGeolocationProvider( 24 net::URLRequestContextGetter* url_context_getter, 25 const GURL& url) 26 : url_context_getter_(url_context_getter), url_(url) { 27} 28 29SimpleGeolocationProvider::~SimpleGeolocationProvider() { 30 DCHECK(thread_checker_.CalledOnValidThread()); 31} 32 33void SimpleGeolocationProvider::RequestGeolocation( 34 base::TimeDelta timeout, 35 SimpleGeolocationRequest::ResponseCallback callback) { 36 DCHECK(thread_checker_.CalledOnValidThread()); 37 SimpleGeolocationRequest* request( 38 new SimpleGeolocationRequest(url_context_getter_.get(), url_, timeout)); 39 requests_.push_back(request); 40 41 // SimpleGeolocationProvider owns all requests. It is safe to pass unretained 42 // "this" because destruction of SimpleGeolocationProvider cancels all 43 // requests. 44 SimpleGeolocationRequest::ResponseCallback callback_tmp( 45 base::Bind(&SimpleGeolocationProvider::OnGeolocationResponse, 46 base::Unretained(this), 47 request, 48 callback)); 49 request->MakeRequest(callback_tmp); 50} 51 52// static 53GURL SimpleGeolocationProvider::DefaultGeolocationProviderURL() { 54 return GURL(kDefaultGeolocationProviderUrl); 55} 56 57void SimpleGeolocationProvider::OnGeolocationResponse( 58 SimpleGeolocationRequest* request, 59 SimpleGeolocationRequest::ResponseCallback callback, 60 const Geoposition& geoposition, 61 bool server_error, 62 const base::TimeDelta elapsed) { 63 DCHECK(thread_checker_.CalledOnValidThread()); 64 65 callback.Run(geoposition, server_error, elapsed); 66 67 ScopedVector<SimpleGeolocationRequest>::iterator new_end = 68 std::remove(requests_.begin(), requests_.end(), request); 69 DCHECK_EQ(std::distance(new_end, requests_.end()), 1); 70 requests_.erase(new_end, requests_.end()); 71} 72 73} // namespace chromeos 74