whitebear
whitebear

Reputation: 12423

Get the position where user indicates

I am using google map API. I successeed in showing the google map in html.

Now, I want to let user select the position and get the latitude/longitude data.

This is the step I supposed.

  1. user will right/left click on a certain point on the map.
  2. an marker appears on the map.
  3. user can move the marker for a minor adjustment.
  4. The longitude/latitude data will appear in textbox.

In generally speaking.

How do I carry out the purpose that 'Let user select the one place on google map and get the geo-information'

For now my code is like this below, simply show the map on HTML

function mapInit() {
    var centerPosition = new google.maps.LatLng(35.656956, 139.695518);
    var option = {
        zoom : 18,
        center : centerPosition,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    };
    var googlemap = new google.maps.Map(document.getElementById("mapField"), option);
}

mapInit();

in html

<div id="mapField" style="width:350px;height:350px;"></div>

Upvotes: 3

Views: 183

Answers (1)

bcdan
bcdan

Reputation: 1428

Please see this Google Maps Documentation Example: https://developers.google.com/maps/documentation/javascript/elevation. In principle, this is exactly what you are looking for. It can be simplified quite a bit to fit your purposes. You only need to add this after the googlemap statement:

var marker = new google.maps.Marker({position:centerPosition, icon:icon_path}); //choose the path for the icon yourself
google.maps.event.addListener(googlemap, 'click', function(event){
  //do whatever you want with this variable of the string of the clicked location:
  event.latLng.toString();
  marker.setPosition(event.latLng);
}

What this does is declare a new event listener from the google.maps library, assign it to the map googlemap, declare its type as 'click' (it is fired when the user clicks) and the final function is a callback, which takes its argument from the click event. The event argument has an attribute called latLng, which is an instance of the google.maps.LatLng library. Meanwhile, a marker is created, and its position changes each time the user clicks. See the Marker documentation (https://developers.google.com/maps/documentation/javascript/reference#Marker) and some usage tutorials (https://developers.google.com/maps/documentation/javascript/markers).

I hope this helps

Upvotes: 2

Related Questions