Coder Social home page Coder Social logo

googlemaps / google-maps-services-go Goto Github PK

View Code? Open in Web Editor NEW
698.0 698.0 213.0 739 KB

Go client library for Google Maps API Web Services

Home Page: https://pkg.go.dev/googlemaps.github.io/maps

License: Apache License 2.0

Go 100.00%
client-library golang google-maps

google-maps-services-go's People

Contributors

alphawong avatar amuramoto avatar arriolac avatar broady avatar cristaloleg avatar deuteu avatar domesticmouse avatar ebati avatar encobrain avatar googlemaps-bot avatar jpoehnelt avatar makkes avatar markmcd avatar marksonghurst avatar mekegi avatar mgmcintyre avatar oanogin avatar oscarzhou avatar peergynt avatar pranas avatar requilence avatar rgaquino avatar ryankurte avatar samthor avatar sarahmaddox avatar savolro avatar scheca avatar shaunmitchellve avatar stephenmcd avatar wangela avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-maps-services-go's Issues

The internal sub-package cannot be retrieved

go version go1.6 darwin/amd64
glide version 0.9.3

This problem surfaced when I attempted to update my glide.lock file with a new dependency using the latest version of Glide (0.9.3). The contents of my glide.yaml follow:

package: github.com/urlgrey/streammarker-data-access
import:
- package: github.com/aws/aws-sdk-go
  version: 4f9a300f2af32035b3ae8bd0ce9b0fe8412df743
  subpackages:
  - aws
  - internal/endpoints
  - internal/protocol/json/jsonutil
  - internal/protocol/jsonrpc
  - internal/protocol/rest
  - internal/signer/v4
  - service/dynamodb
  - aws/awserr
- package: github.com/codegangsta/negroni
  version: c7477ad8e330bef55bf1ebe300cf8aa67c492d1b
- package: github.com/gorilla/context
  version: 215affda49addc4c8ef7e2534915df2c8c35c6cd
- package: github.com/gorilla/mux
  version: 8096f47503459bcc74d1f4c487b7e6e42e5746b5
- package: github.com/mholt/binding
  version: 6c082304f300fc70793cb0be18af0fdd4acd2b75
- package: github.com/stretchr/testify
  version: e22aedd37671fb115be6c0c25129c405cb575cfd
  subpackages:
  - assert
- package: github.com/vaughan0/go-ini
  version: a98ad7ee00ec53921f08832bc06ecf7fd600e6a1
- package: golang.org/x/net
  version: 195180cfebf7362bd243a52477697895128c8777
  subpackages:
  - context
- package: github.com/patrickmn/go-cache
  version: 1881a9bccb818787f68c52bfba648c6cf34c34fa
- package: googlemaps.github.io/maps
  version: b286da8ee62f92267b9cc685fea7f006b80be4ad
- package: github.com/phyber/negroni-gzip
  subpackages:
  - /gzip

Note that the dependency on the Google Maps client uses the googlemaps.github.io domain, as suggested in the project README.md.

I ran glide update to update the glide.lock file:

$ glide update
[INFO] Downloading dependencies. Please wait...
[INFO] Fetching updates for github.com/aws/aws-sdk-go.
[INFO] Fetching updates for github.com/codegangsta/negroni.
[INFO] Fetching updates for github.com/gorilla/mux.
[INFO] Fetching updates for github.com/phyber/negroni-gzip.
[INFO] Fetching updates for github.com/patrickmn/go-cache.
[INFO] Fetching updates for github.com/mholt/binding.
[INFO] Fetching updates for github.com/gorilla/context.
[INFO] Fetching updates for github.com/vaughan0/go-ini.
[INFO] Fetching updates for googlemaps.github.io/maps.
[INFO] Fetching updates for golang.org/x/net.
[INFO] Fetching updates for github.com/stretchr/testify.
[INFO] Setting version for github.com/aws/aws-sdk-go to 4f9a300f2af32035b3ae8bd0ce9b0fe8412df743.
[INFO] Setting version for github.com/codegangsta/negroni to c7477ad8e330bef55bf1ebe300cf8aa67c492d1b.
[INFO] Setting version for github.com/mholt/binding to 6c082304f300fc70793cb0be18af0fdd4acd2b75.
[INFO] Setting version for github.com/gorilla/mux to 8096f47503459bcc74d1f4c487b7e6e42e5746b5.
[INFO] Setting version for github.com/vaughan0/go-ini to a98ad7ee00ec53921f08832bc06ecf7fd600e6a1.
[INFO] Setting version for googlemaps.github.io/maps to b286da8ee62f92267b9cc685fea7f006b80be4ad.
[INFO] Setting version for github.com/stretchr/testify to e22aedd37671fb115be6c0c25129c405cb575cfd.
[INFO] Setting version for github.com/gorilla/context to 215affda49addc4c8ef7e2534915df2c8c35c6cd.
[INFO] Setting version for github.com/patrickmn/go-cache to 1881a9bccb818787f68c52bfba648c6cf34c34fa.
[INFO] Setting version for golang.org/x/net to 195180cfebf7362bd243a52477697895128c8777.
[INFO] Resolving imports
[INFO] Fetching updates for googlemaps.github.io/maps/internal.
[WARN] googlemaps.github.io/maps/internal appears to be a vendored package. Unable to update. Consider the '--update-vendored' flag.
[WARN] Unable to set verion on googlemaps.github.io/maps/internal to . Err: Cannot detect VCS
[INFO] Fetching updates for github.com/go-ini/ini.
[INFO] Fetching updates for github.com/jmespath/go-jmespath.
[INFO] Downloading dependencies. Please wait...
[INFO] Setting references for remaining imports
[ERROR] Failed to set version on googlemaps.github.io/maps/internal to : Cannot detect VCS
[INFO] Project relies on 14 dependencies.
An Error has occurred

This can also be reproduced by running go get on the internal package (make sure it's not already present on your GOPATH):

$ go get -u googlemaps.github.io/maps/internal
package googlemaps.github.io/maps/internal: unrecognized import path "googlemaps.github.io/maps/internal" (parse https://googlemaps.github.io/maps/internal?go-get=1: no go-import meta tags)

The googlemaps.github.io/maps/internal package returns an HTTP 404 response. There are redirects in place for googlemaps.github.io/maps/, but not googlemaps.github.io/maps/internal. This will cause problems for package managers like Glide that perform a recursive traversal of dependencies and go get them from the origin, not the GOPATH.

I think this can be fixed by establishing a redirect for the googlemaps.github.io/maps/internal path.

problem: Self import is not allowed

trying to make other modifications to the code I found this error.
"solve: Self import is not allowed"

Clearly, it is an error when importing.
Ref img:
image

[staticmaps]: It seems the implementation of styled maps is broken

HI there!

I've faced with some problems during using of styled maps.
Let's say I want to send a query that would contain following fields:

  • feature:all|element:geometry|color:0xeeaabb|visibility:simplified
  • feature:all|element:labels.icon|saturation:-50|weight:2
  • feature:water|element:geometry.fill|color:0xff0000
  • feature:landscape.natural|element:geometry|color:0x0000ff|width:50

I'm creating following request:

r := StaticMapRequest{
		Size: "600x600",
		Markers: []Marker{
			Marker{
				Location: []LatLng{
					LatLng{
						Lat: 51.477222,
						Lng: 0,
					},
				},
			},
		},
		MapStyles: MapStyle{
			"all": Elements{
				"geometry": StyleRules{
					"color":      "0xeeaabb",
					"visibility": "simplified",
				},
				"labels.icon": StyleRules{
					"saturation": "-50",
					"weight":     "2",
				},
			},
			"water": Elements{
				"geometry.fill": StyleRules{
					"color": "0xFF0000",
				},
			},
			"landscape.natural": Elements{
				"geometry": StyleRules{
					"color": "0x0000FF",
					"width": "50",
				},
			},
		},
	}

It generates the following URL:

key=<YOUR API KEY HERE>&markers=51.477222,0&size=600x600&style=feature:all||labels.icon|weight:2|weight:2|geometry|visibility:simplified|visibility:simplified&style=feature:water||geometry.fill|color:0xFF0000&style=feature:landscape.natural||geometry|width:50|width:50

There are a few problems here:

  • I got strange duplicates. ( e.g. weight:2|weight:2 )
  • style has double vertical bar between feature and geometry

One extra problem:
AFAIU, the part that contains feature all is invalid at all ( please correct me if i'm wrong ): I expect that the result url would look like: ...style=feature:all|element:geometry|color:0xeeaabb|visibility:simplified&style=feature:all|element:labels.icon|saturation:-50|weight:2... ( according to the doc I can't merge elements with different rules inside the same feature like style=feature:all|element:geometry|color:0xeeaabb|visibility:simplified|element:labels.icon|saturation:-50|weight:2 )

That leads me to the question: is it correct to have a map map[FeatureName]Elements where FeatureName might repeat, and the resulting URL has to contain a single style argument for each requested FeatureName?

I would fix it, but we have to discuss the most appropriate way of fixing.
Thanks!

migrate LatLng to Location

Instead of the LatLng object (with properties Lat and Lng), we'd like to only expose Location, which has properties Latitude and Longitude, for developer consistency.

We can provide internal encoding magic for the older APIs (aka, non-Roads) that use the old type.

Problem when trying to use this library via the new Go modules

Hi,
I have a Go 1.11 project here outside the Go path using the new Go modules.
I executed go get googlemaps.github.io/maps and tried to run an example importing "googlemaps.github.io/maps". But if I want to compile it now, I get this error:

../../golang/pkg/mod/googlemaps.github.io/[email protected]/client.go:30:2: unknown import path "googlemaps.github.io/maps/internal": ambiguous import: found googlemaps.github.io/maps/internal in multiple modules:
googlemaps.github.io/maps v0.0.0-20180903024753-bc340667705e (/Users/philiplb/golang/pkg/mod/googlemaps.github.io/[email protected]/internal)
googlemaps.github.io/maps/internal v0.0.0-20180903024753-bc340667705e (/Users/philiplb/golang/pkg/mod/googlemaps.github.io/maps/[email protected])

Is there anything I'm doing wrong here or how could I make this work?

Errors ignored in DecodePolyline

Looks like errors are printed to stderr instead of returned in the polyline decoder:

https://github.com/googlemaps/google-maps-services-go/blob/master/polyline.go#L49

This means it's not possible to tell if the whole polyline was successfully decoded.

A nicer API would be to propagate the errors up (and leave logging to stderr to the caller)

edit: actually this is log.Fatal, so if you try and parse an invalid polyline it will call os.Exit(1) - which seems non-ideal..

containsLocation function

I have been playing with the library for a while and wanted to check if a given latitude and longitude falls outside a polygon.

This is what the containsLocation function already does using the google map javascript api, wanted to know if there is any method in this package that can help with that.

accept4: too many open files; retrying in 1s

I am using google places api to inside a loop and after 100k loops I always get this error:
[HTTP Server] http: Accept error: accept tcp :443: accept4: too many open files; retrying in 1s

I am using 2 apis inside the loop: PlaceAutocomplete and PlaceDetails, any thoughts?

How to use WithClientIDAndSignature()

Hi there!

I'm wondering how to generate the signature to pass to this function. According to the Geodata API docs, it should be an encoded version of the url I'm calling, but since I'm using google-maps-services-go I don't deal directly with urls.

Alice

syntax error

Hey guys,

I'm getting this when installing the package:

$ go get googlemaps.github.io/maps
# googlemaps.github.io/maps
../../go/src/googlemaps.github.io/maps/client.go:71: syntax error: unexpected range, expecting {
../../go/src/googlemaps.github.io/maps/client.go:76: non-declaration statement outside function body
../../go/src/googlemaps.github.io/maps/client.go:77: syntax error: unexpected }

My system:

$ go version
go version go1.3.3 linux/amd64
$ uname -a
Linux rg-tp 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux

Got any ideas what happened there?
Does

 for range time.Tick(time.Second / time.Duration(c.requestsPerSecond)) {

from client.go:71 use a language feature not yet available in 1.3.3?
The code

for _ = range time.Tick(time.Second / time.Duration(c.requestsPerSecond)) {

works for me. The docs say Go version 1.x or newer is fine.

Allow *Cilent to opt-out of ratelimiting?

Is there some way to disable the builtin ratelimiting started in NewClient()?

Our calling pattern makes it hard to share clients across requests, and so we would prefer to create a new client per request and do our own higher-level ratelimiting.

AFAICT the current implementation of NewClient() starts a goroutine which will never exit, since the ratelimiter channel it feeds is never closed. Additionally, it seems to be using time.Tick(), in which case the ticker 'cannot be recovered by the garbage collector; it "leaks,"' (time Godoc) so we leak 2 things per client.

Am I misunderstanding the code? If not, is there some way I'm overlooking to close the ratelimiter-related resources, or disable it entirely? If not that, then how do you feel about my adding it?

Error handling

Errors are not differentiated so handling different errors is not possible right now.

As an example, OVER_QUERY_LIMIT error is returned from google but can not be checked (this will not be an issue for single instance as rate limiting will prevent this case but can be an issue if multiple instances are running. ZERO_RESULTS is also handled and return empty response for geocoding but it is not handled for other requests (like reverse geocoding).

commonResponse might be made public with defined status list and returned errors can be checked for type match. Or errors can be differentiated like temprory etc. and implements Temprory function (like http package).

If agreed on a solution i can work on the issue.

Making Client an interface, so that it could be mocked

Hi
I'm using this package to use google maps, but I have a problem: I'm using a singleton Client object for all my requests, but Client isn't an interface, so I don't know how can I mock it for unit testing, as is required by github.com/golang/mock or github.com/vektra/mockery.
Do I have to wrap it in another interface and object to be able to mock it?

High CPU usage

maps.NewClient seems have some dead lock inside
If we call geocode mutiple time that the cpu will keep increace.

runtime.futex will use a lot of cpu.

Can Auther provide the benchmark of the maps.NewClient?

Showing top 10 nodes out of 186
      flat  flat%   sum%        cum   cum%
    1450ms 45.03% 45.03%     1450ms 45.03%  runtime.futex /usr/local/go/src/runtime/sys_linux_amd64.s
     280ms  8.70% 53.73%      280ms  8.70%  runtime.usleep /usr/local/go/src/runtime/sys_linux_amd64.s
     130ms  4.04% 57.76%      130ms  4.04%  runtime.siftdownTimer /usr/local/go/src/runtime/time.go
     120ms  3.73% 61.49%      120ms  3.73%  runtime._ExternalCode /usr/local/go/src/runtime/proc.go
     110ms  3.42% 64.91%      120ms  3.73%  syscall.Syscall /usr/local/go/src/syscall/asm_linux_amd64.s
      70ms  2.17% 67.08%     1460ms 45.34%  runtime.timerproc /usr/local/go/src/runtime/time.go
      60ms  1.86% 68.94%       60ms  1.86%  runtime.acquirep /usr/local/go/src/runtime/proc.go
      50ms  1.55% 70.50%       70ms  2.17%  runtime.scanobject /usr/local/go/src/runtime/mgcmark.go
      40ms  1.24% 71.74%       40ms  1.24%  runtime.lock /usr/local/go/src/runtime/lock_futex.go
      40ms  1.24% 72.98%      110ms  3.42%  runtime.mallocgc /usr/local/go/src/runtime/malloc.go

After I switch to https://github.com/martinlindhe/google-geolocate

      flat  flat%   sum%        cum   cum%
      70ms  5.79%  5.79%       70ms  5.79%  runtime.usleep /usr/local/go/src/runtime/sys_linux_amd64.s
      50ms  4.13%  9.92%       50ms  4.13%  syscall.Syscall /usr/local/go/src/syscall/asm_linux_amd64.s
      40ms  3.31% 13.22%       40ms  3.31%  runtime.futex /usr/local/go/src/runtime/sys_linux_amd64.s
      40ms  3.31% 16.53%       40ms  3.31%  runtime.memmove /usr/local/go/src/runtime/memmove_amd64.s
      30ms  2.48% 19.01%       30ms  2.48%  crypto/elliptic.p256Sqr /usr/local/go/src/crypto/elliptic/p256_asm_amd64.s
      30ms  2.48% 21.49%       30ms  2.48%  encoding/json.stateInString /usr/local/go/src/encoding/json/scanner.go
      30ms  2.48% 23.97%       30ms  2.48%  p256MulInternal /usr/local/go/src/crypto/elliptic/p256_asm_amd64.s
      30ms  2.48% 26.45%       30ms  2.48%  runtime.heapBitsSetType /usr/local/go/src/runtime/mbitmap.go
      20ms  1.65% 28.10%       20ms  1.65%  crypto/sha256.block /usr/local/go/src/crypto/sha256/sha256block_amd64.s
      20ms  1.65% 29.75%       20ms  1.65%  runtime.duffcopy /usr/local/go/src/runtime/duff_amd64.s

Reverse Geocoding by Place ID is currently not possible

The Google Maps Gecoding API allows reverse geocoding using either a lat-long combination, or a place_id.

https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding

This is currently not possible to do due to two reasons

  1. The GeocodingRequest does not have a "place_id" field.
  2. The Geocode() function checks if the Address, Components and LatLng are all empty, before making the request. This is completely valid for a reverse geocoding request, which requires either a lat-long or a place_id

I've sent a pull request #75 , which fixes both these issues. Have added a PlaceID field to the GeocodingRequest struct, and added a ReverseGeocode() method as well.

Please have a look. Thanks.

TextSearch with PageToken returns INVALID_REQUEST error

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"googlemaps.github.io/maps"
)

func main() {
	ctx := context.Background()

	client, err := maps.NewClient(maps.WithAPIKey(os.Getenv("GOOGLE_MAPS_KEY")))
	if err != nil {
		log.Fatal(err)
	}

	req1 := &maps.TextSearchRequest{
		Query: "Apartment Buildings New York",
	}

	resp1, err := client.TextSearch(ctx, req1)
	if err != nil {
		log.Fatal(err)
	}

	req2 := &maps.TextSearchRequest{
		PageToken: resp1.NextPageToken,
	}

	_, err = client.TextSearch(ctx, req2)

	if err.Error() == "maps: INVALID_REQUEST - " {
		fmt.Println("we have some bug :)")
	}
}

Can't install using govendor

If I try to run:'m getting this

go get googlemaps.github.io/maps
can't load package: package googlemaps.github.io/maps: no Go files in /Users/myuserhere/Documents/Projects/Go/src/googlemaps.github.io/maps

I've tried to go get this repository, but there are internal imports that refers to googlemaps.github.io

client.go prefill causing batch of queries to hit 'over qps' limit

Hi there.

I am using this library for direction requests.

Over a given day i have noticed in my google for work logs i am hitting the query limit.

With the query per seconds set at 10 in the library. I get a inconsistent amount of requests coming through with the OVER_QPS_LIMIT over the day. I believe this limit is enforced in part due to system load on google servers?

I believe this is caused by the following prefill line in client.go?

I have attached a sample wireshark log which shows that the prefill is making 10 request occur instantly, followed by the correct rate after that (a request every 200 milliseconds).

Thoughts?

Golang Directions SDK does not optimize waypoints

The Directions API does not optimize waypoints when the request specifies Optimize: true.

The issue is that the golang SDK adds optimize=true as its own query parameter, when it should be part of the waypoints query parameter as optimize:true|....

Example of working URL from https://developers.google.com/maps/documentation/directions/intro#Waypoints:

https://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&key=YOUR_API_KEY

The issue here is that https://github.com/googlemaps/google-maps-services-go/blob/master/directions.go#L91 adds optimize as a separate query parameter, rather than appending the waypoint string "optimize:true".

The result is a broken URL:

https://maps.googleapis.com/maps/api/directions/json?optimize=true&origin=Adelaide,SA&destination=Adelaide,SA&waypoints=Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&key=YOUR_API_KEY

cannot get duration_in_traffic

	r := &maps.DistanceMatrixRequest{
		Origins:       strings.Split(origins, "|"),
		Destinations:  strings.Split(destinations, "|"),
		Language:      "en",
		DepartureTime: "now",
		Mode:          maps.TravelModeDriving,
		Units:         maps.UnitsMetric,
	}

	resp, err := client.DistanceMatrix(context.Background(), r)
	if err != nil {
		return c.JSON(http.StatusBadRequest, err)
	}

	return c.JSON(http.StatusOK, resp)

Google Distance Matrix API is returning walking distance even though Mode:transit and TransitMode:train,subway are specified

Sample coordinates are Shibuya Station to Shinjuku Station, should be roughly 9 min travel time by train:

    c, err := maps.NewClient(maps.WithAPIKey("api-key"))
    if err != nil {
        log.Fatal(err)
    }   

    r := maps.DistanceMatrixRequest{
        Origins:      []string{"35.658336, 139.701774"},
        Destinations: []string{"35.690823, 139.699579"},
        Mode:        maps.TravelModeTransit,
        TransitMode: []maps.TransitMode{maps.TransitModeTrain, maps.TransitModeSubway},
    }   
    fmt.Printf("%#v\n", r)
    dmr, err := c.DistanceMatrix(context.Background(), &r) 
    if err != nil {
        log.Fatal(err)
    }   
    for _, row := range dmr.Rows {
        for _, elem := range row.Elements {
            fmt.Println(elem.Status, elem.Duration, elem.Distance.HumanReadable)
        }   
    }  
➜  ~  go run foo.go 
maps.DistanceMatrixRequest{Origins:[]string{"35.658336, 139.701774"}, Destinations:[]string{"35.690823, 139.699579"}, Mode:"transit", Language:"", Avoid:"", Units:"", DepartureTime:"", ArrivalTime:"", TrafficModel:"", TransitMode:[]maps.TransitMode{"train", "subway"}, TransitRoutingPreference:""}
OK 51m25s 4.3 km

Is there something I'm missing?

geolocation bug

geolocation.go
line 63
LocationAreaCode string json:"locatonAreaCode,omitempty"

has to be:
LocationAreaCode string json:"locationAreaCode,omitempty"

missing i :)

Support multiple country filters in places autocomplete API

According to components parameters description at https://developers.google.com/places/web-service/autocomplete#place_autocomplete_requests it is allowed to specify country component multiple times (like e.g. components=country:US|country:FR) - this would result in filtering by any of specified countries.

But currently golang API supports only single value for each component (e.g. country) - corresponding params are passed as golang map:

// Components is a grouping of places to which you would like to restrict your results. Currently, you can use components to filter by country.
Components map[Component]string

It would be helpful to enhance golang API somehow so that multiple values could be passed for country component.

Not sure what would be the best way - maybe we could add another field for components parameter (like slice of pairs or smth similar), or support some special syntax inside given string (thus encoding list as bunch of e.g. comma-separated values), or smth else..

What do you think?

ZERO_RESULTS not an error

For now, when geocoding request have response status ZERO_RESULTS, it is considered as error.

Looks really strange, since it is not an error.
On such response status my service will response 204 for example.
When status 'OK' - then just response 200
In another cases it is really error and I want log it and response 500

I see only one way to achieve it - 'if err != nil && err == "maps: ZERO_RESULTS - "' and it is really ugly.

I have call "result, err := c.Geocode(context.Background(), r)". Any idea how to make it not so ugly?

For me more natural looks PR to Geocode func, that will check if response status "ZERO_RESULTS", than just return empty results. Is such PR have change to be merged, since it will broke backward compatibility?

Shorten comment line length

I'm trying to build a DistanceMatrixRequest and noticed the comments which describe the fields in the struct are pretty long. They're too long to fit into the default godoc boxes [1] or the larger github code viewer [2]. As a result, to read things like the available TransitMode options you need to horizontally scroll.

Reducing the length of the comments and wrapping them earlier would improve ease of use. WDYT?

[1] https://godoc.org/googlemaps.github.io/maps#DistanceMatrixRequest
[2] https://github.com/googlemaps/google-maps-services-go/blob/master/distancematrix.go#L112

Unable to get DurationInTraffic from DistanceMatrix

Same problem as #150

I'm trying to get duration_in_traffic field from Distance Matrix API, which is documented here: https://developers.google.com/maps/documentation/distance-matrix/intro#duration_in_traffic

According to documentation, I think I'm setting the required parameters for that field to be returned:

        r := &maps.DistanceMatrixRequest{
                Origins:       []string{fmt.Sprintf("%.7f,%.7f", lat1, lng1)},
                Destinations:  []string{fmt.Sprintf("%.7f,%.7f", lat2, lng2)},
                Mode:          maps.TravelModeDriving,
                Units:         maps.UnitsMetric,
                DepartureTime: "now", 
                TrafficModel:  maps.TrafficModelBestGuess,
        }
        distMatrix, err := c.DistanceMatrix(context.Background(), r)
        if err != nil {
                return nil, fmt.Errorf("Error getting response from google maps distance matrix api: %v", err)
        }
        bJson, _ := json.Marshal(distMatrix.Rows[0].Elements[0])
        log.Println(string(bJson))

Output:

{"status":"OK","distance":{"text":"2.0 km","value":2007},"duration":"value":298,"text":"4m58s"},"duration_in_traffic":null}

If I test with same api-key with curl, I do get data in that field:

$ curl 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=19.3021022,-99.2298197&destinations=19.51018,-99.12585&mode=driving&units=metric&departure_time=now&traffic_model=best_guess&key=*********************'
{
   "destination_addresses" : [
      "Av Instituto Politécnico Nacional 3600, San Pedro Zacatenco, 07360 Ciudad de México, CDMX, Mexico"
   ],
   "origin_addresses" : [
      "Cto. Fuentes del Pedregal 555, Los Framboyanes, 14150 Ciudad de México, CDMX, Mexico"
   ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "30.5 km",
                  "value" : 30529
               },
               "duration" : {
                  "text" : "48 mins",
                  "value" : 2890
               },
               "duration_in_traffic" : {
                  "text" : "1 hour 6 mins",
                  "value" : 3942
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Remove duplicate leading slash from requests

Seeing loads of these in the logs - e.g.

+------------+-------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+
| Date       | request                                                                                                                                   | UserAgent                                  |
+------------+-------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+
| 2015-07-23 | GET //maps/api/directions/json?destination=Parramatta&key=AIzaNotReallyAnAPIKey&origin=Sydney HTTP/1.1                                    | GoogleGeoApiClientGo/0.1,gzip(gfe)         |
| 2015-07-23 | GET //maps/api/elevation/json?key=AIzaNotReallyAnAPIKey&path=enc%3Acgg~E%7C%7B~pUfcaAwe%7CG&samples=3 HTTP/1.1                            | GoogleGeoApiClientGo/0.1,gzip(gfe)         |
+------------+-------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+

Reports are showing them as 'Other' API calls and while I can fix the reports I'd rather not have to cater for every possible error condition when it's coming from a pseudo-first-party client library.

[question]: Making signing logic exported

Hi there!

I want to ask about "internal" package with signing logic.

As premium users, we need to sign our requests to StaticMap API ourselves (https://developers.google.com/maps/documentation/maps-static/get-api-key#premium-auth), but at the same time, we don't want to store "secret key" in mobile apps due to security reason.

It would be great to have an ability to use SignURL func from outside, cause we have to copy/paste or implement the same somewhere aside.

Is it possible to move signing logic to the root or make internal package exported (and name it "signer" for example)?

Thank you!

Distance matrix is returning wrong distance between two adresses in Canada.

so i had implemented a functionality in my website which requires calculation of distance between two points.However i am getting wrong distance (which is actually much larger than the actual distance between the two locations).
here is the query url which was giving wrong result.
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=%221439%20King%20Street%20West,%20Toronto,%20ON%20%22&destinations=%22254%20Seaton%20Street,%20Toronto,%20ON%22&key=API_KEY

textsearch mismatch between Places API and Go maps package

Today I've tried using TextSearch from this package and failed.

This is what guide states about query parameter

This parameter becomes optional if the type parameter is also used in the search request.

(see https://developers.google.com/places/web-service/search?authuser=1#TextSearchRequests)
Calling API with type parameter without query defined works as well.

But this exception is missing in Go code and this function always returns an error if I want to use type instead of query. (see googlemaps.github.io\maps\places.go:181)

func (c *Client) TextSearch(ctx context.Context, r *TextSearchRequest) (PlacesSearchResponse, error) {

	if r.Query == "" && r.PageToken == "" {
		return PlacesSearchResponse{}, errors.New("maps: Query and PageToken both missing")
	}
       ...

Is this a defect?

Bug - Polyline decoding

Summary

If byte value of 63 ('?' character) appears in encoded string the decoded LatLng slice is not correct.

Steps to reproduce

Run the code below. (You can check the correctness of the expected LatLng slice from here)

package main

import (
	"log"

	"googlemaps.github.io/maps"
)

const routeWith0b = "ynkrFq|zfE?sCnBpA"
const epsilon = 0.0001

var expectedWith0b = []maps.LatLng{{Lat: 39.87709, Lng: 32.74713}, {Lat: 39.87709, Lng: 32.74787}, {Lat: 39.87653, Lng: 32.74746}}

func main() {
	decoded := maps.DecodePolyline(routeWith0b)
	if len(decoded) != len(expectedWith0b) {
		log.Println("expected equal encoding for 0 change in one direction length mismatch, was len %v, expected len %v", len(decoded), len(expectedWith0b))
	}
	for i := range decoded {
		if expected, actual := (expectedWith0b[i]), (decoded[i]); !expected.AlmostEqual(&actual, epsilon) {
			log.Println("expected equal encoding for 0 change in one direction mismatch coordinate, was %+v, expected %+v", decoded, expectedWith0b)
			break
		}
	}
}

StaticMaps doesn't work with coordonates for Center

I am trying to use Lat and Lng instead of address, but it doesn't work, here is my code:

r := &maps.StaticMapRequest{
	Center: "44.4267674,26.102538399999958",
        Size:   "600x300",
	Zoom:   10,
}

This location should be in Bucharest Romania, but instead I get some other location in America.

How I solved it; in staticmap.go I changed this:

if r.Center != "" {
	q.Set("center", url.QueryEscape(r.Center))
}

to this:

if r.Center != "" {
	q.Set("center", r.Center)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.