Search code examples
javascripturlgoogle-maps-api-3google-maps-urls

How to use maps url query with google maps api v3?


I have html page(www.mywebsite/index) with javascript google maps api implementation at it. So i am interested if there is any way to work with queries like https://www.google.com/maps/search/?api=1&query=47.5951518,-122.3316393 at google maps, but at my page, where there are not only map, but other elements too. So i am looking for some way to proceed queries at my page, maybe throught php to give that information directly to map before page load.

Code for index right now is like that:

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <meta charset="UTF-8">
     <meta name="viewport" content=" width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <style>
      #map{
        height:900px;
      }
    #html,body{
    height: 100%;
        margin: 0;
        padding: 0;}

    #floating-panel {
        position: absolute;
        top: 10px;
        left: 8%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      } 
    <style>
      #map{
        height:900px;
      }
    #html,body{
    height: 100%;
        margin: 0;
        padding: 0;}

    #floating-panel {
        position: absolute;
        top: 10px;
        left: 8%;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
        text-align: center;
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      } 
    </style>

     <script>
           var map;
          //empty arrays for filling with active markers and polylines
       var markers = [];    
       var polys =[];

      var oneP = [
       {lat:48.618871,lng: 22.297566},
       {lat:48.618186,lng: 22.298707},
       {lat:48.617063,lng: 22.299621},
       {lat:48.612928,lng: 22.302788}
      ];

      // Array of markers
      var zups = [
        {coords:{lat:48.618776,lng: 22.297590 },title:'<h2>Place 1 </h2><br></br><h3> 1, 2, 3, 12, 20 </h3>'},
        {coords:{lat:48.611788,lng: 22.303622 },title:'<h2>Place 2 </h2><br></br><h3> 1,9, 10,20,21 </h3>'},
        {coords:{lat:48.608147,lng: 22.306452 },title:'<h2>Place 3 </h2><br></br><h3> 1,9,10,20,21 </h3>'},
        {coords:{lat:48.604397,lng: 22.309360 },title:'<h2> Place 4 </h2><br></br><h3> 1,9,10,20,21 </h3>'},
        {coords:{lat:48.599380,lng: 22.313260 },title:'<h2>Place 5</h2><br></br><h3>  1,9,10,20,21 </h3>'},
        {coords:{lat:48.591408,lng: 22.319969 },title:'<h2>Place 6 </h2><br></br><h3> 1 </h3>'}
      ];

    function initMap(){
      // Map options
      var options = {
        zoom:13,
        center:{lat:48.620837,lng:22.287864}
      }
      // New map
      map = new google.maps.Map(document.getElementById('map'), options);
      }

    function addPoly(coords){
        Poly = new google.maps.Polyline({
        path:coords,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
        });
    polys.push(Poly);   
    }

    function SetPolyOnMap(map){
        for (var i = 0; i < polys.length; i++) 
        {
          polys[i].setMap(map);
        }
    }

    // Removes the markers from the map, but keeps them in the array.
      function clearPoly() {
        SetPolyOnMap(null);
      }

      // Shows any markers currently in the array.
      function showPoly() {
        SetPolyOnMap(map);
      }

      // Deletes all markers in the array by removing references to them.
      function deletePoly() {
        clearPoly();
        polys = [];
      }

      // Add Marker Function
      function addMarker(props){
        var marker = new google.maps.Marker({
          position:props.coords,
          map:map,
          title:props.title
        }); 

        // Check for customicon
      //  if(props.iconImage){
          // Set icon image
       //   marker.setIcon(props.iconImage);
       // }

        // Check content
        if(props.title){
          var infoWindow = new google.maps.InfoWindow({
            content:props.title 
          });

          marker.addListener('click', function(){
            infoWindow.open(map, marker);
          });
        }

      markers.push(marker);
      }

      function addMarkersIn(a,b){
       for(var i=a-1;i<b;i++){
        addMarker(zups[i]);}
      }

      // Sets the map on all markers in the array.
      function setMapOnAll(map) {
        for (var i = 0; i < markers.length; i++) {
          markers[i].setMap(map);
        }
      }

      // Removes the markers from the map, but keeps them in the array.
      function clearMarkers() {
        setMapOnAll(null);
      }

      // Shows any markers currently in the array.
      function showMarkers() {
        setMapOnAll(map);
      }

      // Deletes all markers in the array by removing references to them.
      function deleteMarkers() {
        clearMarkers();
        markers = [];
      }

     function one(){
        deleteMarkers();
        deletePoly();
        addMarkersIn(1,6);
        addPoly(oneP);
        showPoly();
        showMarkers();
    }

  </script>
  <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap">
    </script>
</head>
<body>
    <div id="floating-panel">
      <input onclick="one();" type=button value="1">
    </div>  
  <div id="map"></div>   
</body>
</html> 

Solution

  • Just make these changes to your code add the below mentioned method to your code:

     function getQueryParams() {
        // get the param 'query from url'
        var query = location.search.split('query=')[1];
        // if url has any parameter called 'query'
        if (query){
        // get the value of query and split it
        var coords = query.split(',');
        // separate lat and lng and return
        return {hasCoords: true,coords:{lat: parseFloat(coords[0]), lng: parseFloat(coords[1])}};
        } else {
        // if url do not have any parameter called 'query'
        return {hasCoords: false};
        }
    }
    

    This method gets and parse the parameter called 'query' from the page url.

    And modify the initMap() method to something like this.

    function initMap(){
      var coordsInQuery = getQueryParams(); 
      // Map options
      var options = {
        zoom:13,
        center:(coordsInQuery.hasCoords)?coordsInQuery:{lat:48.620837,lng:22.287864}
      }
      // New map
      map = new google.maps.Map(document.getElementById('map'), options);
      }
    

    Now you can pass the coordinates to the page by passing the parameter 'query' to pre-set the location on the map.

    for eg: your-domain/?query=47.5951518,-122.3316393