Calling a JavaScript function in PHP for Google Map - php

hopefully you can help me. I have read a lot of forums regarding this but still cannot get what I wanted. I'm using PHP/MySQL to run my system. I already had a code in JavaScript that will allow the user to add a place and the system can add that place in the Google Map (embedded in my site) as a marker. Now, what I wanted is to add the coordinates of that new place in my database and then my map will just get the markers from the database for adding in the map.
Currently, what I did is to get the latitude and longitude of the added place from the javascript then was able to pass them to my php script within the same file. The latitude and longitude can be added in my database but I do not know now how to go back again to JavaScript so that I can add my markers.
What is the best way to do this? Is/Are there better approaches to solve this?
<?php
$marker = array();
if(isset($_GET['set'])){
$lat = $_GET['lat'];
$long = $_GET['longi'];
$newadd = $_GET['newAdd'];
$connect = mysql_connect("localhost","root","");
mysql_select_db("mapping");
$query=mysql_query("INSERT INTO markers VALUES('','','$newadd','$lat','$long','')");
}
?>
My JavaScript to place markers
function addMarkers(){
var tempMarker;
var tabs = [];
var blueIcon = new GIcon(G_DEFAULT_ICON);
blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/green-dot.png";
// Set up our GMarkerOptions object
markerOptions = { icon:blueIcon };
// for loop get data from db and loop it
tempMarker = new GMarker(tempLatLng,markerOptions);
//if(tabs.length==0){
tabs[ctr] = [new GInfoWindowTab('Greetings','Hi! Welcome'), new GInfoWindowTab('My Info',tempMarker.getLatLng().toString())];
//}
tabInfoWindow(tempMarker,tabs, ctr);
markerArray.push(tempMarker);
displayMarkers();
}
}
Thanks!

Using jquery you can post the data in an ajax request and continue adding the markers in the success handler.
var location = {lat:56, lng:67, name:"my_place"};
$.ajax({
url: "save_place.php",
data: location,
dataType:"json",
success: function(response){
if(response.success){
// add marker to map here
}else{
alert("Error adding location to database");
}
},
error:function(){
alert("Error in connecting to server");
}
});
EDIT:
From your comments, I understand what you need is this one:
<?php
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$long = isset($_GET['longi']) ? $_GET['longi'] : 0;
$newadd = isset($_GET['newAdd']) ? $_GET['newAdd'] : "";
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<style type='text/css'>
#map {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div id="map"></div>
<script type='text/javascript'>//<![CDATA[
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(55, 11),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function addMarker(lat, lng, newAdd) {
alert(" Adding marker " + lat + "," + lng);
this.lat = lat;
this.long = lng;
var location = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
position: location,
title: name,
map: map,
draggable: true
});
map.setCenter(location);
}
<?php
echo "addMarker($lat, $long, '$newadd')";
?>
</script>
</body>
</html>
url : http://<domain>/test.php?lat=40.735812&longi=-74.001389&newAdd=

Well what I do is have a endpoint on the PHP side that I can ask for the markers. Then when my map has loaded I will make a call to get them and then add them on:
$.post('/server/getMarkers',{},function(markers) {
for(var i=0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(marker[i].latitude, marker[i].longitude),
id:marker[i].id
});
google.maps.event.addListener(marker, "click", function() {
//request data for this.id to show in info window if needed
});
}
});
The getMarkers method on the PHP side could look something like this
public function getMarkers() {
/* fetch an array of markers details from the db by any means... */
$markers = getMarkersFromDB();
foreach ($markers as $key=> $marker) {
$payload[$key]['latitude'] = $marker->latitude;
$payload[$key]['longitude'] = $marker->longitude;
$payload[$key]['id'] = $marker->id;
}
echo json_encode($payload);
}

Related

saving marker data into db

How to save a google maps marker data into mysql DB ? using php .
And is it possible to prevent dragging that marker out of a certain country ? or maybe validating if the data is out of the wanted country when clicking on submit for example.
Yes, no problem.
The database part, you will have to do yourself. I provide you 'ajax.php'; where you receive the POST data. All I do, is print the SQL-string.
The country is Belgium, feel free to change this (now on line 39). When ever the client drops the marker anywhere but in Belgium, the marker is sent back to the position where the client started dragging
ajax.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO markers (lat, lng) VALUES (". (float) $_POST['lat'] .", ". (float) $_POST['lng'] .");";
echo $sql;
}
?>
index.php
<div id="map-canvas"></div>
<div class="controls">
<input type="button" value="SAVE" id="save_marker">
</div>
<div id="display"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script>
///////////////////////
// Ajax / upload part
$(document).ready(function() {
// initialize Google Maps
initialize();
// save marker to database
$('#save_marker').click(function() {
// we read the position of the marker and send it via AJAX
var position = marker.getPosition();
$.ajax({
url: 'ajax.php',
type: 'post',
data: {
lat: position.lat(),
lng: position.lng()
},
success: function(response) {
// we print the INSERT query to #display
$('#display').html(response);
}
});
});
});
///////////////////////
//Google Maps part
var map = null;
var marker = null;
var country = 'BE'; // Belgium. Feel free to use this script on any other country
// Google Maps
function initialize() {
var startDragPosition = null;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(50.5, 4.5), // Over Belgium
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// set the new marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(50.5, 4.5),
map: map,
draggable: true
});
var myGeocoder = new google.maps.Geocoder();
// set a callback for the start and end of dragging
google.maps.event.addListener(marker,'dragstart',function(event) {
// we remember the position from which the marker started.
// If the marker is dropped in an other country, we will set the marker back to this position
startDragPosition = marker.getPosition();
});
google.maps.event.addListener(marker,'dragend',function(event) {
// now we have to see if the country is the right country.
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results[1]) {
var countryMarker = addresComponent('country', results[1], true);
if (country != countryMarker) {
// we set the marker back
marker.setPosition(startDragPosition);
}
}
else {
// geocoder didn't find anything. So let's presume the position is invalid
marker.setPosition(startDragPosition);
}
});
});
}
/**
* geocodeResponse is an object full of address data.
* This function will "fish" for the right value
*
* example: type = 'postal_code' =>
* geocodeResponse.address_components[5].types[1] = 'postal_code'
* geocodeResponse.address_components[5].long_name = '1000'
*
* type = 'route' =>
* geocodeResponse.address_components[1].types[1] = 'route'
* geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse, shortName) {
for(var i=0; i < geocodeResponse.address_components.length; i++) {
for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
if (geocodeResponse.address_components[i].types[j] == type) {
if (shortName) {
return geocodeResponse.address_components[i].short_name;
}
else {
return geocodeResponse.address_components[i].long_name;
}
}
}
}
return '';
}
</script>
<style>
#map-canvas {
height:400px;
}
</style>

Gmap3 show all the available markers on the map from database?

I am using gmap3 plugin to show google map. In my case I have stored all the information of properties in the database(mysql) with custom markers. Now I want that when the page is loaded it will display all the markers in google map.
For loading googlemap with gmap3 plugin I am using this code
function loadMap() {
jQuery(document).ready(function(){
if(typeof gMap == 'undefined') {
//// CREATES A MAP
gMap = jQuery('#map-canvas');
gMap.gmap3({
map: {
options: {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
streetViewControl: false
}
}
});
}
});
}
and inside div ``map-canvas I can see the map. But can some one kindly tell me how to show all the markers with the positions? Any help and suggestions will be really appreciable. Thanks.
Update
If I am wrong with my codes then someone can show their codes to me. I am using Gmap3 plugin.
I am not sure about this it will work in gmap3 but i use this code for creating my costome icon hope it will help you
In the index.php use this for creating your costom icon pathlike this
<?php
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
$a=array();
while ($row = #mysql_fetch_assoc($result)){ $a='$row[\'type\']'=>array('icon'=>'$row[\'path\']','shadow'=>'$row[\'path2\']')
}
$a=json_encode($a);
?>
it should be done before js file after that
write this
<script>
var customIcons= <?php echo $a; ?>;
</script>
and finally load your map and infoWindowbox() in that function
function infoWindowbox() {
downloadUrl("xml.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,
shadow: icon.shadow,
animation: google.maps.Animation.DROP
});
markerArray.push(marker);
bounds.extend(marker.position);
bindInfoWindow(marker, map, infoWindow, html);
}
map.fitBounds(bounds);
// var markerCluster = new MarkerClusterer(map, markerArray);
});
}
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() {}
gmap3 initializator has a marker attribute that allows you to create markers.
See example with single and multiple markers here:
http://gmap3.net/en/catalog/10-overlays/marker-41
I think this example might help.
Updated:
If you want to read the data like from database (or) xml, You can then make an ajax request to that page (from any page on your site) using jQuery:
I have an example but this is with xml to get the data from xml file.
$.ajax({
url: 'categories.xml (or) your database path',
type: 'get',
success: function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var address = markers[i].getAttribute("address");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point,name,html,category);
map.addOverlay(marker);
}
// == show or hide the categories initially ==
show("theatre");
hide("golf");
hide("info");
// == create the initial sidebar ==
makeSidebar();
});
});
Like this you may get the data from database also through using queries. Try this one atleast you may get the idea.
The gmaps3 plugin documentation shows how to add markers. If you create an options array in php through ajax/json and feed that to the markers: option your markers should be added.

I'm trying to use PHP to add markers to Javascript (Google Maps) but it isn't working the way I have indended it

I'm trying to use PHP to add a custom marker using GET. I can get inside the if statement just fine and the map loads, but this doesn't add a marker, I'm not familiar with Javascript I'm just using the documentation to do what I need to do.
Inside autolocategmap.js it just contains the Javascript to initialize the map and use geolocation to find the user and it works great, the only problem is the marker is not appearing on load or refresh or anything, I'm not even sure if I can append this extra bit of script by just including <script>custom marker</script>, any information would be great thanks.
<?php
/* Include header and config and set variable*/
require_once('config.inc.php');
require_once($rootdir . $dirsubfolder . 'navbar.php');
$route = $_GET['route'];
?>
<?php
/* User wants to retrieve their route */
if ((isset($route)) && (strcmp($route, "sunauto") == 0)) {
?>
<script src="js/autolocategmap.js"></script>
<script>
addMarker('56.742111','-111.481753','Stop 3', 'Arrives at: 6:00am');
</script>
<?php
}
?>
autolocategmap.js:
/**
* Basic Map
*/
$(document).ready(function(){
var map = new GMaps({
div: '#gmap',
lat: 56.744901,
lng: -111.473049,
zoom: 16,
zoomControl : true,
zoomControlOpt: {
style : 'SMALL',
position: 'TOP_LEFT'
},
panControl : false,
});
GMaps.geolocate({
success: function(position) {
map.setCenter(position.coords.latitude, position.coords.longitude);
},
error: function(error) {
alert('Geolocation failed: '+error.message);
},
not_supported: function() {
alert("Your browser does not support geolocation");
}
});
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 150; // Calculate the top offset
$('#gmap').css('height', (h - offsetTop));
}).resize();
});
function addMarker(lat,lng,title,window){
map.addMarker({
lat: lat,
lng: lng,
title: title,
infoWindow: window
});
}
function show_map() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(51.477118, -0.000732),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var checkCoords = new Array();
checkCoords[0] = addMarker(51.477118, -0.000732, 'Royal Observatory, Greenwich, London', map);
checkCoords[1] = addMarker(38.92126, -77.066442, 'US Naval Observatory, Washington, DC', map);
checkCoords[2] = addMarker(48.853499, 2.348090, 'Notre Dame Cathedral, Paris', map);
}
function addMarker(lat, lng, title, map) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
title: title
});
marker.setMap(map);
return (lat + ',' + lng);
}
show_map();
Ok, use that for your js file. It is straight javascript, no jQuery, but it does what you want. You can then play with it to your hearts content.
As for multiple markers. There are many ways they can be handled through loading from whatever sources.
Maybe a good bet would be for the php to create a json feed that the javascript could read in and then loop through.

Google Maps API v3 - Simple but add Geocode of address from php/mysql

I have this simple hello world version of a google map api javascript v3 and it works for a static geocode. My data is normal addresses (i.e. "30 rockefeller center, New York, NY").
This data is being called from with php from a mysql database. I can get the address on the page with something like this...For the purpose of this post, say this would have all info: address, city, state, zip code
<?php echo $row_query_details['address'];?>
So, I need to geocode this info for the map. I'm very comfortable with mysql and php, but not as much with javascript. I have been trial/error and researching this for a couple of days.
I have looked everywhere for a working sample or example and feel like this relatively simple problem must have been asked and answered many times over, but I cannot figure it out!
Thanks in advance.
Here is the code I'm working with:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:500px"></div>
</body>
</html>
Hello and happy anniversary (regarding your question and tutorial).
I am a web-developer and must thank you. I used this tutorial as I currently do not have a way to geocode via submit (lat/long needs to be pulled from address stored in db) as I am consulting an existing site and have minimal access to backend code.
To answer your question regarding marker interactivity, this takes a few easy steps:
1) Provide some content. This is done before declaring the geocoder (var geocoder;):
var contentString =
'line 1'+
'line 2';
2) Underneath the marker declaration ( var marker = new google.maps.Marker({ ), you will need to declare infowindow and add the event listener:
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
Edit:
I have successfully pulled array information from a MySQL database by expanding on your method. My method is here:
1) Basic php below:
include (dbinfo.php)
$result = mysql_query( 'SELECT * FROM table')
$count = 0
2) Setting up google maps API:
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=yourkey&sensor=false">
</script>
3) Geocoding setup below:
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
var latlng = new google.maps.LatLng(yourlat, yourlong); //This is to center the map
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php //Starts while loop so all addresses for the given information will be populated.
while($row = mysql_fetch_array($result)) //instantiates array
{ ?>
geocoder = new google.maps.Geocoder();
var address = '<?php echo $row['address'].', '.$row['city'].', '.$row['state'].', '.$row['zip'].', '.$row['country']; ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//marker generation is done though adding the primary ID to the "marker" variable, so if address "1" has the primary ID of "1", your marker would read "marker1"
var marker<?php print $row['primaryID']; ?> = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "This can be a php variable or whatever you like. It is displayed on hover."
});
//var contentString manages what is seen inside of the popup
var contentString =
'line 1'+
'line 2';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker<?php print $row['primaryID']; ?>, 'click', function() {
infowindow.open(map,marker<?php print $row['primaryID']; ?>);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
<?php
$count++;
} //ends while
?>
}
/*end javascript*/
</script>
Thank you very much again for posting this. It was very useful.
You can use your PHP variable into JavaScript by passing php variables in function initialize().
your body tag will look like below;
For Ex:
<body onload="initialize('<?php echo $row_query_details['address'];?>')">
Then you will use this particular variable in your javascript code, your javascript function will look like below:
<script type="text/javascript">
function initialize(address) {
var G_address = address;
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
</script>
Now you can use this G_address JavaScript variable dynamically in your G-MAP code..
This will be helpful to you..
So, I'm going to answer my own question here. The first answer provided I was not able to utlize. I'm not sure if the answer was incomplete or I just didnt' follow it. Regardless, here's what the code looks like:
First I had my address components pulling from the mysql db and I assigned them variables, like this:
$county = $row_qry['county'];
$address = $row_qry['address'];
$city = $row_qry['city'];
$state = $row_qry['state'];
Then, my google v3 stuff looks like this:
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = '<?php echo $address.', '.$city.', '.$state; ?>';
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
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);
}
});
}
</script>
And that sort of answers my question. There are a couple of issues I still need to resolve, such as (a) how to make the marker be clickable and interactive, and (b) the map flashes a the geocode first defined (34.05,-118.24) before showing the correct address.
Both of these issues I need to still resolve, but at least the geocoding is working successfully. Hope this helps someone else.
Thanks!

Google Maps load issues on PHP page

I'm connecting a Google Map to a MySQL database to list distributors all over the world, and I seem to be having a few issues.
Sometimes the page itself will not load at all in Firefox (v4 on Mac). It's temperamental on my machine (FF v3.6 Mac) and a Windows machine (FF v4 Win 7), ok in Safari/Opera, doesn't load at all in IE 9 (Win 7). Not sure if it's a network issue or code.
Load time is pretty slow. Might be because the map covers the whole page (will create a square block to place it in).
The URL of the page is here and I used the code from Sean Feeney's page.
The code I have is:
<script src="http://maps.google.com/maps?file=api&v=2&key=<I entered my key here>" type="text/javascript"></script>
<body onUnload="GUnload()">
<div id="map" style="position:absolute;top:0px;bottom:0px;left:0;right:0;"></div>
</body>
<script type="text/javascript">
//<![CDATA[
var map;
var latlngbounds;
if (GBrowserIsCompatible()) {
function createMarker(point, address) {
var marker = new GMarker(point);
var html = address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function extendBounding(point) {
latlngbounds.extend(point);
var zoom = map.getBoundsZoomLevel(latlngbounds);
if (zoom < 10) {
zoom = 12;
}
map.setCenter(latlngbounds.getCenter(), zoom);
}
}
map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
latlngbounds = new GLatLngBounds();
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var address = markers[i].getAttribute("address");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, address);
map.addOverlay(marker);
extendBounding(point);
}
});
}
//]]>
</script>
The code that gets the data is the same as the example.
Any ideas as to why it doesn't always load in the browsers, and why it seems to take a while to load?
Thanks,
Adrian
Ideally you should wrap the code that loads the map inside a document ready or window load event.
I notice that your code is not nested properly inside the GBrowserIsCompatible() block so please fix that.
As far as I remember, Google maps API v2 requires you to call the setCenter() method before doing any operations on the map. So to begin with, set the center to (0, 0) immediately after creating the map.
I notice that you're downloading XML data before you add markers to the map. You must take into account the time taken by the server to serve the XML data. If you've called the setCenter() before downloading the XML, the map will display while the XML downloads asynchronously.
Inside the code that handles the XML data: when you add a marker, do not call setCenter() immediately. Doing so will cause the function to be called 1000 times if you have 1000 markers in your XML. Instead, just call latlngbounds.extend(point). Once you have iterated the loop, calculate the zoom/center and call setCenter(). This way you will end up calling this function only twice.
Edit
I've figured out what the problem is. The genxml.php randomly returns the string Google Geo error 620 occurred which cannot be parsed as XML which raises JavaScript errors and no markers are shown. Better have a look at the code of that file and see why this happens randomly. On other times when that file actually returns valid XML, the markers appear as expected.
It appears Google recently tightened geocoding requests. If you send 10 too fast, it cuts you off with 620 error. The solution they recommend is adding a dynamic timer. Other stackoverflow posts suggested a 0.25 second static timer was good enough, but I've found Google's recommendation of using a while loop that increments the timer value as needed works better. For example:
// Initialize delay in geocode speed
public $delay = 0;
public function lookup(arguments)
{
$geocode_pending = true;
while ($geocode_pending) {
$search = //address string to search;
$response = $this->performRequest($search, 'xml');
$xml = new SimpleXMLElement($response);
$status = (int) $xml->Response->Status->code;
switch ($status) {
case self::G_GEO_SUCCESS:
require_once('placemark.php');
$placemarks = array();
foreach ($xml->Response->Placemark as $placemark)
$placemarks[] = Placemark::FromSimpleXml($placemark);
$geocode_pending = false;
return $placemarks;
case self::G_GEO_TOO_MANY_QUERIES:
$delay += 100000;
case self::G_GEO_UNKNOWN_ADDRESS:
case self::G_GEO_UNAVAILABLE_ADDRESS:
return array();
default:
throw new Exception(sprintf('Google Geo error %d occurred', $status));
}
usleep($delay);
}
}
You can run your map code with window.load after everything is loaded:
jQuery(document).ready(function initAutocomplete() {
var p_lag=$('#longitude').val();
var p_lat=$('#latitude').val();
if(p_lat==''){
var p_lat=20.593684;
}
if(p_lag==''){
var p_lag=78.96288000000004 ;
}
var myLatLng = {lat: p_lat,lng: p_lag};
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: myLatLng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
draggable: true,
map: map,
title: 'Map'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
//Click event for getting lat lng
google.maps.event.addListener(map, 'click', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
google.maps.event.addListener(marker, 'dragend', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
/*markers.forEach(function (marker) {
marker.setMap(null);
});*/
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
$('#latitude').val(place.geometry.location.lat());
$('#longitude').val(place.geometry.location.lng());
marker.setPosition(place.geometry.location);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
});
}
);

Categories