How to implement search functionality for Google M

2019-01-28 03:46发布

问题:

I need to implement a search functionality for my Android Google Map Api V2 project and can't find any working example. I just need to enter a city name, press a "Search" button and then the map should move to the city and show a marker on it. Just like the Google Maps application does. Autocompletion should be nice though. I actully get to show the map, show some markers, etc, I just can't get to perform the search and see the results. Please help!

Thanks in advance

回答1:

I just need to enter a city name, press a "Search" button and then the map should move to the city and show a marker on it. Just like the Google Maps application does.

So for that you have to make the functionality on Click of search in which you have to do as follows:

  • The city name entered by the user Will be sent to the google api - It will get back the lat-long to you.
  • You will use that lat-long to add marker as well as,
  • You will use that lat-long to animate the Gmaps Camara. That's it.
  • In this way you are able to fullfill your above requirement.


回答2:

As far as I can see, moving the map to a certain point is done by calling the GoogleMap object's moveCamera() method:

 GoogleMap map = ((MapFragment) getFragmentManager()
            .findFragmentById(R.id.map)).getMap();

 LatLng sydney = new LatLng(-33.867, 151.206);

 map.setMyLocationEnabled(true);
 map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

Taken from this example.

As you can see, you'll need the latitude and longitude coordinates for creating a LatLng object. I believe you can use place search from google to obtain those coordinates, using http-requests. Example:

https://maps.googleapis.com/maps/api/place/textsearch/xml?query=restaurants+in+Sydney&sensor=true&key=AddYourOwnKeyHere

taken from here

which should return JSON-data for you.

For autocomplete, see this link

Edit: Wops, the place search would return xml, try using ...json?query=... instead