I'm trying to make a Google map that updates a marker as a user's location is updated. I have most of it done, but I'm having one small issue. I want one marker that shows the starting point, which I have working, but the second point should keep moving, and it should allow multiple users to be tracked at once.
I can get this to work for one user (sending GPS coordinates from Android app). It will set the start marker, and as their location changes the marker will move to reflect that. My problems occur when I start tracking a second user. The current position marker for the first user becomes the starting location for the second user. It 'jumps' from the first path to the other (see picture). I know this is partly due to the declaration of the 'marker1' variable at the top, but I've tried many things with no luck. I need to be able to create as many as I need for n number of users so I can't declare a bunch of variables for each one.
You can see in the picture what is happening. This is the moment when a new user triggers the tracking function in the app. Before this second user activates the tracking function, the marker for the first user was moving properly.
function initialize() {
var myLatlng = new google.maps.LatLng(39, -86);
var myOptions = {
zoom: 6,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var loc = {};
var mark = {};
var markers = {};
var marker1;
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'api.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var user_id = data[0];
var lati = data[1]; //get id
var longi = data[2]; //get name
var myLatlngt = new google.maps.LatLng(lati, longi);
if (typeof loc[user_id] === 'undefined') {
loc[user_id] = [];
}
//if (typeof markers[user_id] === 'undefined') {
//markers[user_id] = [];
//}
if (typeof mark[user_id] === 'undefined') {
mark[user_id] = myLatlngt;
}
loc[user_id].push(myLatlngt);
//markers[user_id].push(myLatlngt);
var x;
for (x in loc) {
var polyline = new google.maps.Polyline({
map: map,
path: loc[x],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
///location variables
var start_loc = loc[user_id];
var start_marker = start_loc[0]; //start location of given user
var current_loc = start_loc[start_loc.length -1]; //last known location of given user
//set the start marker
var marker = new google.maps.Marker({
position: start_marker,
title: user_id
});
marker.setMap(map);
//update the current location marker
if (marker1 != null) {
marker1.setPosition(current_loc);
}
else {
marker1 = new google.maps.Marker({
position: current_loc,
map: map
});
}
}
//console.log('location :::', x);
console.log('Marker: ', mark);
}
});
}, 1000);
});
});
}
Considering that I don't really know javascript I may be totaly wrong here, but I am assuming that the anonymous function sent as argument to setInterval is called multiple times (?).
If that is the case, I would expect marker1 to be reused since it is declared outside of the function, I.e, it is the same marker1 used for every function call in this part of the code
//update the current location marker
if (marker1 != null) {
marker1.setPosition(current_loc);
}
I guess you could use the same method for the marker1 as you did for the loc, having it as an array indexed by the user ID. (perhaps calling it currentLocationMarker would be a better name too)
Another way would be to have the marker1 only existing within the function, but that may cause all the previous current location markers for a user to be visible. Not sure about that, I do not get the full picture of this system you are building.
It's not totally clear what the issue is, but have you tried using .panTo()? It scrolls smoothly to a new location. Call it after your .setPosition().
if (marker1 != null) {
marker1.setPosition(current_loc);
map.panTo( current_loc );
}
Related
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 have a JavaScript ajax page, which fires an ajax request (using setInterval function) every 20 seconds and gets response in JSON format. In the page; using JSON response I'm displaying the markers on Google map (using API v3) and updating them every 20 seconds based on the location received from ajax response. I'm displaying an infoWindow on click event of marker.
I am using PHP as server side scripting, which generates my ajax response by doing some DB calls.
Everything works fine when I open the page. But slowly the page starts responding slow. I mean when I click on the marker or on related text, page takes a significant time to locate the marker, to load the map and to open the infoWindow. And the slowness of page increases as the time passes. If I refresh the page, again everything starts working fine.
The page don't even show a single error at any point of time and I must add that the auto updation of location of markers works fine throughout the life of the page.
I've tried everything which I found on forums. Like, I've moved to json response from an xml(dom) response. I've tried changing the XMLHttpRequest methods, as the GET requests have tendency to auto cache the data. But nothing helped me. I am completely clueless, what is wrong, what I am doing in my code.
Here is my JavaScript code:
<script type="text/javascript">
var map;
var contentString = "";
var infoWindow = new google.maps.InfoWindow({content: contentString});
var url = "genAjaxResponse.php?id=<?php echo $id; ?>";
var marker;
var gmarkers = new Array();
var icon;
var lastClickedMarker;
var stImgId;
var customIcons = {
Moving: {
icon: 'icons/abc.png'
},
Idle: {
icon: 'icons/xyz.png'
},
Parked: {
icon: 'icons/pqr.png'
},
Alert: {
icon: 'icons/wxy.png'
}
};
function load() { // to be called on onload event of body
map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
center:new google.maps.LatLng(15.570128,78.957092)
});
calldownloadUrl(url,map,infoWindow);
directionsDisplay = new google.maps.DirectionsRenderer();
}
function calldownloadUrl(url,map,infoWindow) {
downloadUrl(url,displayMarker,map,infoWindow);
}
function displayMarker(data,map,infoWindow) {
function generateTriggerCallback(object, eventType) {
return function() {
google.maps.event.trigger(object, eventType);
};
}
var namearr = Array();
var json = data.responseText;
var vehicles = eval ("(" + json + ")");
var i = 0;
for (var veh in vehicles)
{
var tag = vehicles[veh];
var veh_no = tag["veh_no"];
var is_stale = tag["is_stale"];
var ignition_off = tag["ignition_off"];
var speed = tag["speed"];
var lat = tag["lat"];
var lng = tag["lng"];
var time = tag["time_stamp"];
var address = tag["address"];
var point = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng));
var type;
var status;
stImgId = i+1;
if(ignition_off == 0 && speed > 3) {
type = "Moving";
status = type + "(" + speed + " Kmph)";
document.getElementById("img"+stImgId).src = "icons/greenalert2.png";
}
else {
if(ignition_off == 1) {
type = "Parked";
status = type;
document.getElementById("img"+stImgId).src = "icons/greyalert2.png";
}
else {
type = "Idle";
status = type;
document.getElementById("img"+stImgId).src = "icons/yellowalert2.png";
}
}
if(is_stale == 1) {
type = "Alert";
status = type;
document.getElementById("img"+stImgId).src = "icons/redalert2.png";
}
infoWindow.close();
var icon = customIcons[type] || {};
if(typeof gmarkers[i] != 'undefined') {
gmarkers[i].setPosition(point);
gmarkers[i].setIcon(icon.icon);
if(gmarkers[i].id == lastClickedMarker) {
if(map.getBounds().contains(gmarkers[i].getPosition()) === false)
map.setCenter(gmarkers[i].getPosition());
}
}
else
{
gmarkers[i] = new google.maps.Marker({
id: i,
position: point,
icon: icon.icon,
title: veh_no,
map: map
});
}
var html = "<span><p><b>"+veh_no +"</b></p> <p>Address: "+address+"<br />Status: "+status+"<br />Time: "+time+"</p></span>";
namearr[i] = "<span><p><b>"+veh_no +"</b></p> <p>Address: "+address+"<br />Status: "+status+"<br />Time: "+time+"</p></span>";
// -- bind click event to texts (vehicle nos) -- //
var textclick = document.getElementById(i);
textclick.onclick = generateTriggerCallback(gmarkers[i],"click");
// -- bind click event to markers -- //
bindinfoWindow(gmarkers[i], map, infoWindow, namearr[i], icon);
i++;
}
}
function bindinfoWindow(marker, map, infoWindow, html, icon) {
google.maps.event.addListener(marker, 'click', function() {
lastClickedMarker = marker.id;
map.setCenter(marker.getPosition());
if(map.zoom < 15)
map.setZoom(15);
marker.setIcon(icon.icon);
marker.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback, map, infoWindow) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, map, infoWindow, request.status);
}
};
request.open('GET', url, true);
request.send();
}
function doNothing() {}
window.setInterval(function() {calldownloadUrl(url,map,infoWindow)},20000);
</script>
I've a similar app and I've also ran into similar behavior.
In my case, I've been updating an array of markers every 30 secs (for each marker: location, icon, content of a listener).
Firstly, I have stopped creating a new marker each update, I thought that setting markers[id].setMap(null); and creating new one will be OK, that CG will handle this.
Then I've changed the code to only update markers position, icon and listener, like this:
this.markers[id].setPosition(new google.maps.LatLng(lat, lng));
this.markers[id].setIcon(this.updateFlags(status, id));
google.maps.event.addListener(this.markers[id], 'mouseover', function () {
infoWindow.setContent(text);
infoWindow.open(this.map, this);
});
google.maps.event.addListener(this.markers[id], 'click', function () {
devices.selectDevice(index);
});
This produced much less consumed memory, but still...
Finally I've edited code like this:
this.markers[id].setPosition(new google.maps.LatLng(lat, lng));
this.markers[id].setIcon(this.updateFlags(status, id));
google.maps.event.clearListeners(this.markers[id], 'mouseover');
google.maps.event.clearListeners(this.markers[id], 'click');
google.maps.event.addListener(this.markers[id], 'mouseover', function () {
infoWindow.setContent(text);
infoWindow.open(this.map, this);
});
google.maps.event.addListener(this.markers[id], 'click', function () {
devices.selectDevice(index);
});
I've tested it in Chrome Developer Tools (F12) -> Profiler and Take Heap Snapshot. And you will see if it grows too fast.
So in your case it would mean adding this line as the first line of function bindinfoWindow():
google.maps.event.clearListeners(marker, 'click');
I think you need to empty the gmarkers array each time you calling that ajax request, or reset the i variable before you processing the received data. In this way you are not adding all the new markers to the previous ones, which seems is the bottleneck in your code.
P.S. I didn't test your code. I'm just guessing.
I have a Google map that I want to automatically load with a prepopulated route (taken from a series of PHP form submissions).
Currently, the PHP forms culminate in a page that has a Google Map on it, and some drop-down boxes with the start and end points prepopulated (from their previous PHP form submissions), and an onChange function on the drop-down menus which calculates the route (onChange="calcRoute();", in the example below). This works fine but, in reality, every final form ends up with just one option for the route. Therefore, getting the user to "select" the start points and end points for the route is worthless - there is only one option in each drop down menus, so I might as well load those options and the calculated route between them automatically when the page loads.
Is there any way of doing this?
My directions function looks like this:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<?PHP
$Start_latLng = $_POST["start-latitude"] . ", " . $_POST["start-longitude"];
$End_latLng = $_POST["end-latitude"] . ", " . $_POST["end-longitude"];
?>
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(54.219218, -2.905669)
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
...and my dropdown menus are populated by the results of the PHP $_POST functions.
Obviously, I need wait for the map to load before I can calculate the route, so a pause might need to be injected - any ideas?
Thank you to #Robot Woods:
Could you just fire calcRoute(); as the last line of your initialize function? – Robot Woods
I have 2 tables and i have mentioned the fields of it,
1. events:event_id,title,location,latitude,longitude,address,description,link
2. event_time:event_id,start_time,end_time,start_date,end_date,date
i have given the my map code below in that i am trying to get the popup when the particular marker is clicked on the map.when i click on the marker it displays the popup and in popup we retrieve the table datas.
The problem what i have is, i am able to get all the data from database other than description. but when i try to retrieve description the map wont be shown.
the way data is retrieved from the database is also given below in the code.
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
<script type="text/javascript"><script language="javascript">
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var markersArray = [];
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 500,
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup =null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
currentPopup.close();
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map1"), {
center: new google.maps.LatLng(12.972352762582736,77.59734949737549),
zoom:60,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
<?
$query=mysql_query("select * from events join event_time on (events.event_id=event_time.event_id) where events.isapproved='Y'");
while ($row = mysql_fetch_array($query))
{
$title=$row['title'];
$location=$row['location'];
$sdate=$row['start_date'];
$edate=$row['end_date'];
$stime=$row['start_time'];
$end_time=$row['end_time'];
$lat=$row['latitude'];
$lon=$row['longitude'];
$address=$row['address'];
$date=$row['date'];
$de=$row['description'];
$link=$row['link'];
echo ("addMarker($lat,$lon,'$stime ".to."$end_time<br/><br/><b>$title</b><br/><br/>$address<br/><br/>$de<br/><a>$link</a>');\n");
}
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
the map code and retriveing data and displaying it are together.
if anyone knows it,please help me solve this problem.thanks in advance.
I suggest checking the values for Description in your database. Are any characters which are Javascript special values escaped?
For instance, suppose the Description value for one record is:
You can't find a better party than this one!
If you put this in place of $de in your addMarker line above, and leave all the other variables alone, the resulting line of Javascript is:
addMarker($lat,$lon,'$stime to $end_time<br/><br/><b>$title</b><br/><br/>$address<br/><br/>You can't find a better party than this one!<br/><a>$link</a>');
Notice that the apostrophe in "can't" now ends the Javascript string. What the Javascript interpreter sees is code like:
addMarker($lat,$lon,'$stime to $end_time<br/><br/><b>$title</b><br/><br/>$address<br/><br/>You can'
t find a better party than this one!<br/><a>$link</a>');
The first line is an incomplete statement, and the second line starts with the second part of the $de value outside of quotes.
In general, almost all your variable values will be interpreted first as Javascript and then as HTML. Thus, you should escape them according to HTML conventions and then Javascript conventions, in order to be sure they don't disrupt anything.
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);
});
});
}
);