durtsarockz
durtsarockz

Reputation: 3

Show marker based on user-defined Lat/Long in Google Map on button click

First of, newbie here. SO please bear with my question. :)

Let's say I have a location(lat/long) extracted from my database, and I want to use this location as the position of where the marker is plotted in the map. How to do?

I've tried implementing some codes I've found here, but doesn't seem to work for me.

Here's what I have so far:

   var center;
    var myLatlng;
           function initialize() {
               myLatlng = new google.maps.LatLng(document.getElementById("txtLatLng"));
               var mapOptions = {
                   zoom: 12,
                   center: myLatlng
               }
               var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);          

               var marker = new google.maps.Marker({
                   position: myLatlng,
                   map: map
               });

google.maps.event.addDomListener(window, 'load', initialize);

I'm trying to replace the value of myLatLng variable with txtbox value, but no luck.

PS. I'm aware that this is on event load. which leads me to my 2nd question, how to do all of this in event btnClick?

Thanks in advance!

Upvotes: 0

Views: 716

Answers (1)

Anto Jurković
Anto Jurković

Reputation: 11258

Check example at jsbin.

You can use one input field as you started but you have to parse it. I left it there and add basic parsing. That part is not triggered with button click.

For me it's better to have separate input field for latitude and longitude: added two input fields and button which triggers function:

function setMarker() {
    var latitude = latEl.value;
    var longitude = lngEl.value;

    if (latitude == '' || longitude == '') {
        console.log('lat or lng not defined');
        return;
    }

    var position = new google.maps.LatLng(parseFloat(latitude), 
                                          parseFloat(longitude));

    var marker = new google.maps.Marker({
        position: position,
        map:      map
    });

    map.setCenter(position);
}

setCenter() is called to position marker to the center. Otherwise it could happen that it is off the visible part.

Upvotes: 1

Related Questions