0

hi I using PHP/MySQL with Google Maps from here https://developers.google.com/maps/articles/phpsqlajax_v3
and then I used PHP's DOM functions to Output XML from here https://developers.google.com/maps/articles/phpsqlajax_v3#outputxml

everything working fine with me but I need to center google map on the marker.

here is the code that center the map and make the zoom on the map

function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(30.0599153,31.2620199,13),
        zoom: 13,
        mapTypeId: 'roadmap'
      });

how to make this line center: new google.maps.LatLng(30.0599153,31.2620199,13), to be dynamic centered by the marker
thanks

3
Contributors
9
Replies
51
Views
3 Years
Discussion Span
Last Post by johnef_sh
0

Try with:
center = new google.maps.LatLng(30.0599153,31.2620199,13) || map.setCenter(marker.getPosition());

0

I did this center: new google.maps.LatLng(30.0599153,31.2620199,13)||map.setCenter(marker.getPosition()), but still not geting the key marker on the center

0

see the all code maybe this will help

<!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>PHP/MySQL & Google Maps Example</title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    //<![CDATA[

    var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      }
    };
    function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(30.0599153,31.2620199,13)||map.setCenter(marker.getPosition()),
        zoom: 13,
        mapTypeId: 'roadmap'
      });
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("phpsqlajax_genxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
          bindInfoWindow(marker, map, infoWindow, html);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}

    //]]>

  </script>

  </head>

  <body onload="load()">
    <div id="map" style="width: 500px; height: 300px"></div>
  </body>

</html>

0

I am really busy right now here, but regardless this topic is for JS subforums, you should check Marker class, position_changed event and getPosition() method.

Edited by Tpojka

0

@Tpojka I try to follow up with what you give to me but still can not understand how to manage this. please see the src code and even tell me where to add position_change in my code

0

Which marker are you trying to set the center to? If it's one of the markers you get from the XML, which one of them (since there can be more than one)?

1

I don't know are you trying to get map center from details of your DB or dinamically of some marker triggered event.
If it is first case, just add PHP echo in your JS code.
If it is second case, you can use panTo() method.
I've make little function from basic example of gmap v3 you can check:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Map moving to the marker position</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
// The following example creates a marker in 
// Stockholm, Sweden using a DROP animation. 
// Dragging marker on map will set new center position of map.

var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var parliament = new google.maps.LatLng(59.327383, 18.06747);
var marker;
var map;

function initialize() {
  var mapOptions = {
    zoom: 13,
    center: stockholm
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);

  marker = new google.maps.Marker({
    map:map,
    draggable:true,
    animation: google.maps.Animation.DROP,
    position: parliament
  });
  google.maps.event.addListener(marker, 'mouseup', panMapToMarker);
}

function panMapToMarker() {

  if (marker.getPosition() != null) {
    map.panTo(marker.getPosition());
  }
}

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

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

I hope you will find something usefull. Cheers.

edit: I have modified code sample from this page.

Edited by Tpojka

0

Hi @Tpojka and @scudzilla I am very sorry if I didn't make my self clear from the beginning, I am developing a real estates website which the admin can add properties to his projects page now one of the options he should have is to add the place of the property he advertised, so on my CMS pan I have the map which the admin will drop his pin to his specific property and then save this
after that the expected clients who will enter the site will see the pin which the admin put before.

here is my code of the admin section
HTML code

<!DOCTYPE html >
      <head>
        <meta name="viewport"&nbsp;content="initial-scale=1.0, user-scalable=no" />
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Google Maps&nbsp;JavaScript API v3 Example: Map Simple</title>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
        <script type="text/javascript">
        var marker;
        var infowindow;

        function initialize()&nbsp;{
          var latlng&nbsp;= new google.maps.LatLng(30.0599153,31.2620199,13);
          var options&nbsp;= {
            zoom:&nbsp;13,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          }
          var map = new google.maps.Map(document.getElementById("map-canvas"), options);
          var html ;= "<table>" +
                     "<tr><td>Name:</td> <td><input type='text' id='name'/> </td>&nbsp;</tr>" +
                     "<tr><td>Address:</td> <td><input type='text' id='address'/></td>&nbsp;</tr>" +
                     "<tr><td>Type:</td> <td><select id='type'>" +
                     "<option value='bar' SELECTED>bar</option&gt;" +
                     "<option value='restaurant'>restaurant</option&gt;" +
                     "</select> </td></tr>" +
                     "<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
        infowindow = new&nbsp;google.maps.InfoWindow({
         content: html
        });

        google.maps.event.addListener(map, "click", function(event) {
            marker = new google.maps.Marker({
              position: event.latLng,
              map: map
            });
            google.maps.event.addListener(marker, "click", function() {
              infowindow.open(map, marker);
            });
        });
        }

        function saveData() {
          var name ;= escape(document.getElementById("name").value);
          var address&nbsp;= escape(document.getElementById("address").value);
          var type ;= document.getElementById("type").value;
          var latlng&nbsp;= marker.getPosition();

          var url = "phpsqlinfo_addrow.php?name=" + name&nbsp;+ "&address=" + address +
                    "&type="&nbsp;+ type + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
          downloadUrl(url,&nbsp;function(data, responseCode) {
            if&nbsp;(responseCode == 200 && data.length <= 1) {
              infowindow.close();
              document.getElementById("message").innerHTML ;= "Location added.";
            }
          });
        }

        function downloadUrl(url, callback) {
          var request&nbsp;= window.ActiveXObject ?
              new ActiveXObject('Microsoft.XMLHTTP') :
              new XMLHttpRequest;

          request.onreadystatechange = function() {
            if&nbsp;(request.readyState == 4) {
              request.onreadystatechange = doNothing;
              callback(request.responseText, request.status);
            }
          };

          request.open('GET', url, true);
          request.send(null);
        }

        function doNothing() ;{}
        </script>
      </head>

      <body style="margin:0px; padding:0px;" onload="initialize()">
        <div id="map-canvas"&nbsp;style="width: 800px; height: 600px"&gt;</div>
        <div id="message">&lt;/div>
      </body>

    </html>

and then come to the PHP code which manage the dynamic part adding the information to the database

<?php
    // Gets data from URL parameters
    $name = $_GET['name'];
    $address = $_GET['address'];
    $lat = $_GET['lat'];
    $lng = $_GET['lng'];
    $type = $_GET['type'];

    mysql_connect("localhost", "root", "") or
             die("Could not connect: " . mysql_error());
    mysql_select_db("arabia");

    // Insert new row with user data
    $query = sprintf("INSERT INTO markers " .
             " (id, name, address, lat, lng, type ) " .
             " VALUES (NULL, '%s', '%s', '%s', '%s', '%s');",
             mysql_real_escape_string($name),
             mysql_real_escape_string($address),
             mysql_real_escape_string($lat),
             mysql_real_escape_string($lng),
             mysql_real_escape_string($type));

    $result = mysql_query($query);

    if (!$result) {
      die('Invalid query: ' . mysql_error());
    }

    ?>

now come to the clients section

the HTML of the client section

    <!DOCTYPE html >
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>map</title>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
        //<![CDATA[

        var customIcons = {
          restaurant: {
            icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
          },
          bar: {
            icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
          }
        };
        function load() {
          var map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(30.0599153,31.2620199,13)||map.setCenter(marker.getPosition()),
            zoom: 13,
            mapTypeId: 'roadmap'
          });
          var infoWindow = new google.maps.InfoWindow;

          // Change this depending on the name of your PHP file
          downloadUrl("phpsqlajax_genxml.php", function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < markers.length; i++) {
              var name = markers[i].getAttribute("name");
              var address = markers[i].getAttribute("address");
              var type = markers[i].getAttribute("type");
              var point = new google.maps.LatLng(
                  parseFloat(markers[i].getAttribute("lat")),
                  parseFloat(markers[i].getAttribute("lng")));
              var html = "<b>" + name + "</b> <br/>" + address;
              var icon = customIcons[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: icon.icon
              });
              bindInfoWindow(marker, map, infoWindow, html);
            }
          });
        }

        function bindInfoWindow(marker, map, infoWindow, html) {
          google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
          });
        }

        function downloadUrl(url, callback) {
          var request = window.ActiveXObject ?
              new ActiveXObject('Microsoft.XMLHTTP') :
              new XMLHttpRequest;

          request.onreadystatechange = function() {
            if (request.readyState == 4) {
              request.onreadystatechange = doNothing;
              callback(request, request.status);
            }
          };

          request.open('GET', url, true);
          request.send(null);
        }

        function doNothing() {}

        //]]>

      </script>

      </head>

      <body onload="load()">
        <div id="map" style="width: 500px; height: 300px"></div>
      </body>

    </html>

now the last PHP section witch manage getting the data from the database

    <?php  

    // Start XML file, create parent node

    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node); 

    // Opens a connection to a MySQL server

    mysql_connect("localhost", "root", "") or
             die("Could not connect: " . mysql_error());
    mysql_select_db("arabia");

    // Select all the rows in the markers table

    $query = "SELECT * FROM markers WHERE 1";
    $result = mysql_query($query);
    if (!$result) {  
      die('Invalid query: ' . mysql_error());
    } 

    header("Content-type: text/xml"); 

    // Iterate through the rows, adding XML nodes for each

    while ($row = @mysql_fetch_assoc($result)){  
      // ADD TO XML DOCUMENT NODE  
      $node = $dom->createElement("marker");  
      $newnode = $parnode->appendChild($node);   
      $newnode->setAttribute("name",$row['name']);
      $newnode->setAttribute("address", $row['address']);  
      $newnode->setAttribute("lat", $row['lat']);  
      $newnode->setAttribute("lng", $row['lng']);  
      $newnode->setAttribute("type", $row['type']);
    } 

    echo $dom->saveXML();

    ?>

now everything is running fine with this code the whole problem is in this line of code in the HTML of the client view center: new google.maps.LatLng(30.0599153,31.2620199,13)||map.setCenter(marker.getPosition()), which I need it to be centerd on the pin that the admin put before.

thanks for all the reviews and replies

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.