Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google map V3 Set Center to specific Marker

I am using Google Map V3 to display a list of markers pulled from a DB, using MYsql and PHP. MY markers are set on the map using the full address (from DB, including postcode) as I don't have the Long,Lat info All is working fine, MY loop looks as follow

while... Addmarker(map,'MY ADdress','Title'); end while; 

Now I would like to set the map to a specific marker contained in the loop that will match a previously entered postcode. How can I set the map to center to this marker and open the infowindow?

like image 642
salocin Avatar asked May 27 '11 09:05

salocin


People also ask

How do I add a marker to Google Maps Center?

In the "Addmarker" function in your while... end loop you should be building Marker objects using the Google Maps API. You may need to assign each marker (or just the marker(s) you wish to work with) to an array so that you can access them.

How do I mark a specific location?

To mark a location using the mouse cursor, point the cursor to the desired location in the View window, right-click, and select Mark Location. A location marker appears, along with a label displaying the x,y coordinates.


2 Answers

Once you have markers on the map, you can retrieve the Lat/Long coordinates through the API and use this to set the map's center. You'll first just need to determine which marker you wish to center on - I'll leave that up to you.

// "marker" refers to the Marker object you wish to center on  var latLng = marker.getPosition(); // returns LatLng object map.setCenter(latLng); // setCenter takes a LatLng object 

Info windows are separate objects which are typically bound to a marker, so to open the info window you might do something like this (however it will depend on your code):

var infoWindow = marker.infoWindow; // retrieve the InfoWindow object infoWindow.open(map); // Trigger the "open()" method 

Hope this helps.

like image 75
6twenty Avatar answered Oct 21 '22 16:10

6twenty


To build upon @6twenty's answer...I prefer panTo(LatLng) over setCenter(LatLng) as panTo animates for smoother transition to center "if the change is less than both the width and height of the map". https://developers.google.com/maps/documentation/javascript/reference#Map

The below uses Google Maps API v3.

var marker = new google.maps.Marker({     position: new google.maps.LatLng(latitude, longitude),     title: markerTitle,     map: map, }); google.maps.event.addListener(marker, 'click', function () {     map.panTo(marker.getPosition());     //map.setCenter(marker.getPosition()); // sets center without animation }); 
like image 33
Eddie Avatar answered Oct 21 '22 17:10

Eddie