Get the position the user points to

I am using google map API. I was successfully displaying google map in html.

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

This is the step I suggested.

  • the user will right / left click on a specific point on the map.
  • a marker appears on the map.
  • the user can move the marker for minor customization.
  • Longitude / Latitude data appears in the text box.

Generally speaking.

How to fulfill the goal: "Let the user select one place on the Google map and get geo-information"

Now my code looks like this, just show the map in 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>

      

+3


source to share


1 answer


See this example Google Maps documentation: https://developers.google.com/maps/documentation/javascript/elevation . Basically, this is exactly what you are looking for. It can be simplified to suit your goals. You only need to add this after the instruction googlemap

:

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 means is, it declares a new event listener from the google.maps library, assigns it to the map googlemap

, declares its type as 'click'

(it fires when the user clicks), and the final function is a callback that takes an argument from the click event. The argument event

has an attribute latLng

that is an instance of the library google.maps.LatLng

. Meanwhile, a marker is created and its position changes every time the user clicks. See the Markers documentation ( https://developers.google.com/maps/documentation/javascript/reference#Marker ) and some usage guides ( https://developers.google.com/maps/documentation/javascript/markers ) ...

I hope this helps

+2


source







All Articles