red23jordan
red23jordan

Reputation: 2891

how to use javascript to call google map specific location

Suppose I have a html including 2 <div>, one is Google Maps, one is a list
Of course, the maps <div> is displaying the map
the list <div> is is th2 location list(e.g New York, London, etc)
I have one question, How can I click on one location of the list, and then the Maps will go to the specific location?
When onClick the list item, is it use javascript to call Or How can I do such function using Javascript?

Upvotes: 3

Views: 4366

Answers (1)

HandiworkNYC.com
HandiworkNYC.com

Reputation: 11114

I'm using a little bit of jquery to select the elements, call the click function, and get the address from the title attribute.

Check out this jsfiddle for reference:

http://jsfiddle.net/X5r8r/263/

<a class="location" title="New York, NY">New York</a>
<a class="location" title="Los Angeles, CA">Los Angeles</a>
<a class="location" title="Washington District of Columbia">Washington</a>

<div id="map-canvas" title="1600 Washington"></div>

<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>

var geocoder;
var map;
function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(0,0);
    var myOptions = {
         zoom: 17,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
}

function codeAddress(element) {
    var address = element.attr('title');
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                   map: map,
                   position: results[0].geometry.location
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

$(document).ready(function(){
    $map = $('#map-canvas');

    initialize();
    codeAddress($map);

    $('.location').click(function(){
        $me = $(this);
        codeAddress($me);
    });
});

Upvotes: 2

Related Questions