Search code examples
javascriptjquerygoogle-mapsgoogle-maps-api-3geolocation

Current location draggable marker


How can i let the "address" locate a current location marker for the user on google map by clicking on the button rather than take the input value

http://jsfiddle.net/razanrab/WppF6/253/

<body>
  <div id="panel">
      <input id="city_country" type="textbox" value="Berlin, Germany">
      <input type="button" value="Geocode" onclick="codeAddress()">
  </div>  
  <div id="mapCanvas"></div>
  <div id="infoPanel">
    <b>Marker status:</b>
    <div id="markerStatus"><i>Click and drag the marker.</i></div>
    <b>Current position:</b>
    <div id="info"></div>
    <b>Closest matching address:</b>
    <div id="address"></div>
  </div>
</body>


//js 

var geocoder;
var map;
var marker;

codeAddress = function () {
    geocoder = new google.maps.Geocoder();

  var address = document.getElementById('city_country').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 16,
            streetViewControl: false,
          mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
              mapTypeIds:[google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP] 
    },
    center: results[0].geometry.location,
    mapTypeId: google.maps.MapTypeId.

Solution

  • Location code is not working here.In fiddle it is working see link below

    Fiddle Demonstration

    Code below

    // Note: This example requires that you consent to location sharing when
    // prompted by your browser. If you see the error "The Geolocation service
    // failed.", it means you probably did not give permission for the browser to
    // locate you.
    var map, infoWindow;
    var geocoder;
    
    function initMap() {
      geocoder = new google.maps.Geocoder();
      map = new google.maps.Map(document.getElementById('mapCanvas'), {
        center: {
          lat: -34.397,
          lng: 150.644
        },
        zoom: 6
      });
      infoWindow = new google.maps.InfoWindow;
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
    
          var marker = new google.maps.Marker({
            position: pos,
            map: map,
            draggable: true,
            title: 'Your position'
          });
          /*infoWindow.setPosition(pos);
          infoWindow.setContent('Your position');
          marker.addListener('click', function() {
            infoWindow.open(map, marker);
          });
          infoWindow.open(map, marker);*/
          map.setCenter(pos);
    
    
          updateMarkerPosition(marker.getPosition());
          geocodePosition(pos);
    
          // Add dragging event listeners.
          google.maps.event.addListener(marker, 'dragstart', function() {
            updateMarkerAddress('Dragging...');
          });
    
          google.maps.event.addListener(marker, 'drag', function() {
            updateMarkerStatus('Dragging...');
            updateMarkerPosition(marker.getPosition());
          });
    
          google.maps.event.addListener(marker, 'dragend', function() {
            updateMarkerStatus('Drag ended');
            geocodePosition(marker.getPosition());
            map.panTo(marker.getPosition());
          });
    
          google.maps.event.addListener(map, 'click', function(e) {
            updateMarkerPosition(e.latLng);
            geocodePosition(marker.getPosition());
            marker.setPosition(e.latLng);
            map.panTo(marker.getPosition());
          });
    
        }, function() {
          handleLocationError(true, infoWindow, map.getCenter());
        });
      } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
      }
    
    }
    
    function geocodePosition(pos) {
      geocoder.geocode({
        latLng: pos
      }, function(responses) {
        if (responses && responses.length > 0) {
          updateMarkerAddress(responses[0].formatted_address);
        } else {
          updateMarkerAddress('Cannot determine address at this location.');
        }
      });
    }
    
    function updateMarkerStatus(str) {
      document.getElementById('markerStatus').innerHTML = str;
    }
    
    function updateMarkerPosition(latLng) {
      document.getElementById('info').innerHTML = [
        latLng.lat(),
        latLng.lng()
      ].join(', ');
    }
    
    function updateMarkerAddress(str) {
      document.getElementById('address').innerHTML = str;
    }
    
    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
      infoWindow.setPosition(pos);
      infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
      infoWindow.open(map);
    }
    #mapCanvas {
      width: 300px;
      height: 300px;
      float: left;
    }
    
    #infoPanel {
      float: left;
      margin-left: 10px;
    }
    
    #infoPanel div {
      margin-bottom: 5px;
    }
    <div id="panel">
      <!--<input id="city_country" type="textbox" value="Berlin, Germany">-->
      <input type="button" value="Locate Me" onclick="initMap()">
    </div>
    <div id="mapCanvas"></div>
    <div id="infoPanel">
      <b>Marker status:</b>
      <div id="markerStatus"><i>Click and drag the marker.</i></div>
      <b>Current position:</b>
      <div id="info"></div>
      <b>Closest matching address:</b>
      <div id="address"></div>
    </div>
    <!-- Replace the value of the key parameter with your own API key. -->
    <script async defer src="https://maps.googleapis.com/maps/api/js">
    </script>