Goog day!
I have a very simple implementation of google maps, which allows my users to draw polylines anywhere on the map canvas.
When starting afresh, the polyline segments are visible on the map and the polyline is stored inside a mySql database using PHP.
// When editing a map with a polyline:
If a user decides to change the polyline, i load the previous polyline from the database and it is visible to the user. When they click on the button to draw a polyline it wil clear the previous polyline from the map and allow them to start afresh, however, once they start clicking away on the map, the new polyline segments is no visible on the map, but is saves correctly to the database.
Here is what i've done so far:
var map;
var polyline = null;
var polylinePath = null;
// HERE I INITIALIZE MY MAP ETC ETC ...
// IN EDIT MODE I ALLOW THE FOLLOWING FUNCTION TO BE CALLED FIRST TO LOAD ANY EXISITNG POLYLINES FOR THE USER
// THIS WORKS FINE, IT SHOWS THE PREVIOUS POLYLINE ON THE MAP.
function loadBasePolylines($mapGuid)
{
var loadUrl = 'classes/Ajax_System.php';
$.getJSON(loadUrl+"?action=loadMapPolylines&mapId="+mapGuid, function(json) {
if(json[0]['hasPolylines'] == 'yes'){
var polylinesArray = [];
var prepath = polylinePath;
if(prepath){
prepath.setMap(null);
}
var points = json[0].Points;
for (i=0; i<points.length; i++) {
polylinesArray.push(new google.maps.LatLng(points[i].lat,points[i].lon));
bounds.extend(new google.maps.LatLng(points[i].lat,points[i].lon));
}
polyline = new google.maps.Polyline({
strokeColor: json[0]['lineColour'],
strokeOpacity: 0.5,
strokeWeight: json[0]['lineThickness'],
clickable: false,
path: polylinesArray
});
polylinePath = polyline.getPath();
polyline.setMap(map);
map.fitBounds(bounds);
}
});
}
// WHEN THE USER PRESS THE "DRAW PATH" BUTTON, THE FOLLOWING FUNCTION IN QUESTION IS CALLED:
function startPolyline()
{
if(polyline != null){
var answer = confirm("This will clear the current polyline from the map. Are you sure you want to continue?");
if(answer){
polyline.setMap(null);
if (tempMarkers) {
for (i in tempMarkers) {
tempMarkers[i].setMap(null);
}
tempMarkers.length = 0;
}
} else {
return;
}
}
var polyOptions = {
strokeColor: polylineColor,
strokeOpacity: polyLineOpacity,
strokeWeight: polyLineWidth,
clickable: false
}
polyline = new google.maps.Polyline(polyOptions);
polyline.setMap(map);
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addPolylinePoint);
}
function addPolylinePoint(event)
{
var path = polyline.getPath();
path.push(event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
icon: '<?php echo URL; ?>public/mapIcons/mm_20_red.png',
map: map
});
tempMarkers.push(marker);
}
What i've tried so far:
Check the color codes are in correct format: YES
Check Lat Lon order and values: YES
Any help will sincerely be appreciated. Thank you in advance.
Wow, I've solved the disappearing polyline issue after reading through my question again. Hopefully this will help someone out there one day:
In my code where i load the polylines from the database:
function loadBasePolylines($mapGuid)
{
.
.
.
polyline = new google.maps.Polyline({
strokeColor: json[0]['lineColour'],
strokeOpacity: 0.5,
strokeWeight: json[0]['lineThickness'],
clickable: false,
path: polylinesArray
});
}
I set the stroke opacity to 0.5 (Equal to 50%) right...
But then, just when i start the polyline tool in ...
function startPolyline()
var polyOptions = {
strokeColor: polylineColor,
strokeOpacity: polyLineOpacity,
strokeWeight: polyLineWidth,
clickable: false
}
... i set the opacity to an unset variable called polyLineOpacity.
Once i added the global variable and applied the loaded value in ...
function loadBasePolylines($mapGuid)
{
.
.
.
strokeOpacity = json[0]['lineOpacity'] * 100;
polyline = new google.maps.Polyline({
strokeColor: json[0]['lineColour'],
strokeOpacity: strokeOpacity,
strokeWeight: json[0]['lineThickness'],
clickable: false,
path: polylinesArray
});
}
... the polylines with the correct opacity displayed correctly again!
I call this developers brain-freeze.
Tkx!
try reinitiating the map variable in the startPolyline function
map = new google.maps.Map(document.getElementById('id of your map')):
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'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.
I want to know how to make some sort of event in javascript that will be triggered ever time when new data is inserted?
I need this so I can use live tracking in google maps.
For example this is the code that I have found on geolocation page:
function scrollMap(position)
{
// Scrolls the map so that it is centered at (position.coords.latitude,position.coords.longitude).
}
// Request repeated updates.
var watchId = navigator.geolocation.watchPosition(scrollMap);
function buttonClickHandler()
{
// Cancel the updates when the user clicks a button.
//I want to put my code in here so for example when I click button live tracking starts.
navigator.geolocation.clearWatch(watchId);
}
This is my code that I am using to retrieve array of the data:
function initialize() {
var myLatLng = new google.maps.LatLng(0, 180);
var myOptions = {
zoom: 3,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var flightPlanCoordinates = [<?php echo implode(',', $coordinates) ?>];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
How can I make my code to work and get one last result every time it is inserted in the database? And show it on the map in the google code that is provided at the begining of my question.
Database is mysql it has ID,Latitude and Longitude.
EDIT:
This is my PHP code that fetches all data from database and put them in the array for google maps:
$coordinates = array();
$result = dbMySql::Exec('SELECT Latitude,Longitude FROM data');
while ($row = mysqli_fetch_assoc($result))
$coordinates[] = 'new google.maps.LatLng(' . $row['Latitude'] . ', ' . $row['Longitude'] . ')';
The simplest solution is to poll your server. Ask for entries created within the last X minutes and add the new entries.
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 );
}
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);
});
});
}
);