How to change the position on the map each time the user clicks a link?

Asked

Viewed 1,739 times

2

I need to display a map and just below would have a list with multiple addresses and when clicking on each address would be marked in Google Maps the place. I already did a search on the net but I couldn’t find anything I could rely on.

  • What are you building? A web page? An app? A desktop application?

  • It is on a website. The company has office in several different cities and to show where each office is wanted to do so. But I can’t find anything online to help me.

  • Can you already create the map and only need to centralize? Which code is already ready?

2 answers

4

One way is by defining latitude and longitude with attributes data-*. You may have an element <a> with the following marking:

<a href='#' data-latitude='-xx.xxx' data-longitude='-yy.yyy'>Endereço, 123</a>

Using Javascript you can get these two information. A simple example, with jQuery:

$('a').on('click', function(){
   var lat = $(this).data('latitude'),
       lon = $(this).data('longitude');

       alert("Latitude: " + lat + ". Longitude: " + lon);
});

And then create a new location for Google Maps.

meuMapa.panTo(new google.maps.LatLng(lat,lon));



Follow an example code:

$(function () {
  
  var $map = $("#map-view").get(0),
 
  // latitude e longitude inicial
  latlon = new google.maps.LatLng(28.617161,77.208111);
  
  var gmap = new google.maps.Map($map, {
    center: latlon,
    zoom: 10
  });
  
  var marker = new google.maps.Marker({
    position: latlon,
    map: gmap,
    title: 'Rajya Sabha'
  });
                
  
  $('.map-nav a').on('click', function(){
    var lat = $(this).data('lat'),
        lon = $(this).data('lon');
    
    // obtem a nova latitude/longitude
    var newLatLon = new google.maps.LatLng(lat,lon);
    
    gmap.panTo(newLatLon); // muda a posição do mapa pra nova localização
    marker.setPosition(newLatLon); // altera a posição do marcador
    marker.setTitle($(this).html()) // altera o título do marcador
  });
});
/* Somente para melhorar a visualização */
#map-view{ width: 100%; height: 250px }
.map-nav {width: 100%; background: #333; padding: 8px 0; text-align:center}
.map-nav a{ text-decoration: none; color: #fff;margin: 0 15px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp'></script>

<nav class='map-nav'>
  <a href='#' data-lat='-3.11903' data-lon='-60.02173'>Manaus, AM</a>
  <a href='#' data-lat='-25.42895' data-lon='-49.26714'>Curitiba, PR</a>
  <a href='#' data-lat='-12.97304' data-lon='-38.50230'>Salvador, BA</a>
</nav>
<div id='map-view'></div>


Data Attributes [W3C]
Data Attributes [MDN]

  • Could you trade jQuery for pure JS? The question does not mention jQuery.

  • @bfavaretto So that much of the code is hidden, I thought the question was how to do logic and my suggestion was: data Attributes.

  • I get it. My fear is that it will eventually induce other people to use jQuery just to solve something like this (of course when the library is already in use in the project for other purposes, it makes more sense to use it in this case too, but we don’t know the situation of AP or other future readers).

  • 1

    Maybe I’m overreacting to trying to protect the world from over-searching the web :)

3


This is the example of a basic map that is part of the Google Maps documentation:

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
var map;
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}

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

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

This code creates an object map, of the kind google.maps.Map. To change the center, just call the setCenter of that object, passing latitude and logitude. These values can be defined:

  1. As a google.maps.LatLng:

    var posicao = new google.maps.LatLng(-35, 151);
    
  2. Or as a literal object:

    var posicao = {lat: -34, lng: 151};
    

With this, just pass the position to center:

map.setCenter(posicao);
  • But how can I manipulate it? And add other values? Basically what I need to do is like this: http://jsfiddle.net/dUMFW/5/

  • Each link of this must contain a different address and change there on the map and that’s exactly what I’m not able to do.

  • Now @rrnan has explained that part, so I’m not going to add it here. But you could have clarified that right away, no? From what you wrote there, you couldn’t know exactly where your difficulty was.

  • sorry I misinterpreted, I didn’t know exactly how to explain this.

  • @And I’m sorry if my comment sounded disrespectful. It is that here on the site we like that the questions are very clear and objective, focused. Thus, a question and its answers end up being useful to much more people than who originally asked. So please take this into account in the next question ok? And good learning :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.