jagmitg
jagmitg

Reputation: 4546

Google Map API - Autocomplete search on current map

I have got a map which has its own data set - so its loading additional information from an external API, filling in on the custom google map.

I am using the auto select functionality from google so when the user searches for the a certain address or location, they are zoomed in on the current map (without losing all the data points)

So with this function, the output is correct:

London 51.5073509 -0.12775829999998223 6 

My question - Query is, how can i get the following:

console.log(defaultArea + ' ' + defaultLat + ' ' + defaultLng + ' ' + defaultZoom);

Into the current map.

I have tried - still doesnt work.

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

Current JQUERY:

var defaultLat = 54
defaultLng = -4,
defaultZoom = 6,
defaultArea = null;

function searchFunct() {
    var input = document.getElementById('location');
    var options = {
      types: ['(regions)'],
      componentRestrictions: {
          country: 'uk'
      }
    };

    var autocomplete = new google.maps.places.Autocomplete(input, options);

    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var place = autocomplete.getPlace();
        document.getElementById('city2').value = place.name;
        document.getElementById('cityLat').value = place.geometry.location.lat();
        document.getElementById('cityLng').value = place.geometry.location.lng();

        var citi = document.getElementById('city2').value;
        var lati = document.getElementById('cityLat').value;
        var longi = document.getElementById('cityLng').value;

        defaultArea = citi;
        defaultLat = lati;
        defaultLng = longi;
        defaultZoom = 6;

        console.log(defaultArea + ' ' + defaultLat + ' ' + defaultLng + ' ' + defaultZoom);

    });
}

Upvotes: 0

Views: 196

Answers (1)

jagmitg
jagmitg

Reputation: 4546

Add the following underneath the console.log

All i did there is declare a variable defining your latitude and longitude within the google map variable google.maps.LatLng. Secondly, declared a myOptions object to define where input is being taken. Finally, plot all those on the map_canvas and add a marker on there.

var latlng = new google.maps.LatLng(defaultLat, defaultLng);
var myOptions = {
    zoom: 11,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById("map_canvas"),
   myOptions);

marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: 'Main map'
});

Upvotes: 0

Related Questions