Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change the centre of a google maps without erasing markers?

Initially, my map would be pointing to the user's current location. I am giving an option where in he can choose a city from an auto complete box, once he selects the new location from auto complete, I will get a new (lat,lng) coordinates for which I would like to focus my map to.

From my knowledge of Maps API, I am able to think of it as changing the centre(however, the centre is set only while loading the map). I want to achieve this focus to user selected location on google maps. Can some one help me out. Thanks in advance. Using Google Maps js api v3.

like image 706
Vamshi Vangapally Avatar asked Sep 23 '12 17:09

Vamshi Vangapally


People also ask

How do I move a marker on Google Maps?

JavaScript Code The initialize() function creates a Google Map with a marker. The transition() and moveMarker() are used to move marker smoothly on click on the Google map.

How do I move a marker smoothly on Google Maps?

initialize() function creates a google Map with location Marker. transition() & moveMarker() are used to move location marker smoothly on Google Map.

Is Google Maps dynamic or static?

The Google Maps Platform static web APIs let you embed a Google Maps image on your web page without requiring JavaScript or any dynamic page loading. The APIs create an image based on URL parameters sent through a standard HTTP request and allow you to display the result on your web page.


2 Answers

You can simply move the map with map.setCenter(LatLng). This method will not use any other markers and will not erase existing markers. You could also move the map via the panTo(LatLng) function. Both methods are also available after the map has been initialized.

Here is the documentation for these methods.

like image 142
j0nes Avatar answered Sep 29 '22 03:09

j0nes


jOnes is right, you need to use setCenter()

function initialize() {     var mapDiv = document.getElementById('MapDiv');     var map;     var address = "Vilnius, Lithuania";     var geocoder = new google.maps.Geocoder();     // Get LatLng information by name     geocoder.geocode({         "address": address         }, function(results, status){                 map = new google.maps.Map(mapDiv, {                 // Center map (but check status of geocoder)                 center: results[0].geometry.location,                 zoom: 8,                 mapTypeId: google.maps.MapTypeId.ROADMAP,             })         }); } 
like image 39
Aleksej Vasinov Avatar answered Sep 29 '22 04:09

Aleksej Vasinov