Geolocation coords not passing from javascript to php - javascript

Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.
Here the code.
1.code from template-maps.php:
var pos;
var posZae = function(pos){
return {
coords: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
accuracy: pos.coords.accuracy.toFixed()
},
timestamp: pos.timestamp
}
};
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
var netPOS = JSON.stringify(posZae(position));
$.ajax({
type: 'POST',
data: { 'pos' : pos},
url: '/wp-content/themes/honolulu/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
it should send the data to template-userslocation.phpwhere I have this code:
<?php
/**
* Template Name: template-userslocation
*/
$lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
$lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>
I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.
Solved:
The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.
Here the info

EDIT 2
I have no idea about any WordPress plugins or PHP. Does the lat/lng appear on the network/at the server? Anyway try this: -
var posZae = function(pos){
return {
lat: pos.coords.latitude,
lng: pos.coords.longitude,
}
};
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = posZae(position);
var netPOS = JSON.stringify(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
$.ajax({
type: 'POST',
data: { 'pos' : netPos},
url: '/wp-content/themes/honolulu/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
EDIT 1
OK would this ring any bells of familiarity with you?
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
var netPOS = JSON.stringify(pos4Net(position));
$.ajax({
type: 'POST',
data: { 'pos' : netPOS},
url: '/wp-content/themes/atripby/template-userslocation.php'
});
ORIGINAL POST:
Not sure where you "pos" is declared. Maybe localizing it with VAR will help instantiate it?
I've had the same/similar problem with the nature of the position object and call the following before trying to transmit it over the network: -
var pos4Net =
function(pos)
{
return {
coords: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
accuracy: pos.coords.accuracy.toFixed()
},
timestamp: pos.timestamp
}
}
So var yourPos = pos4Net(position)

there is no data. Nothing in the page and in the console.
Your PHP code copies the POSTed data into a couple of variables. That is all.
It doesn't output anything. It doesn't use the variables for anything.
It just stores in the data in variables, then exits (which destroys the variables because they only exist for the lifetime of the program execution).
You need to do something with the data.
You could just output it straight back:
<?php header("Content-Type: text/plain"); echo $lat; echo $lng; ?>
… which isn't very useful, but serves as a demonstration.
Your JavaScript does nothing with the response.
(The response, as mentioned above, doesn't contain anything, so you need to fix the PHP first).
You have no success handler in your JavaScript, so when the browser gets the response, your code doesn't do anything with it. This is why nothing is shown in the browser.
url: '/wp-content/themes/atripby/template-userslocation.php'
}).done(function(data) { console.log(data); });
… would show the results in the browser's developer tools console.

first console your lat. and lang. to check if you get any result then use the following code in ajax
data: { 'lang' : coordinates , 'lat': coordinate},
then use $_POST['lant'] and $_POST['lang'] in destination file

The ajax function is sending pos which is an object but you are using array notation within the php script to access the lat/lng.
Perhaps if you did
$.ajax({
type: 'POST',
data: { lat:pos.lat, lng:pos.lng },
url: '/wp-content/themes/atripby/template-userslocation.php'
});
You could then, in the PHP, try
$lat=!empty( $_POST['lat'] ) ? $_POST['lat'] : null;
$lng=!empty( $_POST['lng'] ) ? $_POST['lng'] : null;

Related

Get Specific location with longitude and latitude value saved in localhost of specific address with Mapbox in laravel 08

I am making the website with food ordering and delivering module. For that I am using Mapbox and here first i want to select the store-address location with longitude and latitude which i want to select from my addresses table.I dont know how to display the address-location with the longitude and latitude of specific store-address and show with the marker.
Here is the code of the Controller function for getting the value of longitude and latitude of specific address with id :
public function mapofstore($id)
{
$data = DB::Table('addresses')->select('longitude','latitude')->where('id',$id)->get();
// dd($data);
return view('MainAdmin.frontend.reports.storelocation',compact('data'));
}
Here is the code of javascript reference from the official doc of Mapbox:
<div class="container">
<div class="map-area">
<div id='map' style=" width:100%; height: 500px; border: solid;border-color: #1e828de8;border-radius: 1%;"></div>
<pre id="info"></pre>
</div>
</div>
<script>
mapboxgl.accessToken = 'My_MapBox_Api';
var map = new mapboxgl.Map({
container: 'map',
style: 'Style_URL'
});
navigator.geolocation.getCurrentPosition(successLocation,errorLocation,{
enableHighAccuracy: true
})
function successLocation(){
console.log(position)
}
function errorLocation(){
}
function getReverseGeocodingData(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, (results, status) =>{
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
}
});
}
function onClick(event){
document.getElementById('lat').value = event.latlng.lat;
document.getElementById('lng').value = event.latlng.lng;
var group = L.featureGroup();
group.id = 'group';
var p_base = L.circleMarker([event.latlng.lat ,event.latlng.lng], {
color: '#fff',
fillColor: '#6a97cb',
fillOpacity: 1,
weight: 1,
radius: 6
}).addTo(group);
map.addLayer(group);
}
// function START for getting lng,lat of current mouse position----------------
map.on('mousemove', (e) => {
document.getElementById('info').innerHTML =
// `e.point` is the x, y coordinates of the `mousemove` event
// relative to the top-left corner of the map.
JSON.stringify(e.point) +
'<br />' +
// `e.lngLat` is the longitude, latitude geographical position of the event.
JSON.stringify(e.lngLat.wrap());
});
// function END for getting lng,lat of current mouse position------------------
// function START for getting current location----------------
map.addControl(new mapboxgl.NavigationControl());
map.addControl(
new mapboxgl.GeolocateControl({
positionOption:{
enableHighAccuracy:true
},
trackUserLocation:true
}));
// function END for getting current location------------------
// function for Direction and Pointing of one Point-----------
map.addControl(
new MapboxDirections({
accessToken: mapboxgl.accessToken
}),
'top-left'
);
const addMarker = () => {
const marker = new mapboxgl.Marker()
// const minPopup = new mapboxgl.Popup({closeButton: false, closeOnClick: false})
minPopup.setHTML("")
marker.setPopup(minPopup)
marker.setLngLat([36.67981,22.10816])
marker.addTo(map)
marker.togglePopup();
}
map.on("load",addMarker)
$.getJSON("https://jsonip.com?callback=?", function (data) {
var ip = data;
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// console.log(url);
$.ajax({
url : '{{URL::to('updateip')}}' + '/' + id,
type: 'POST',
data: {_token: CSRF_TOKEN,
"ip": ip,
"id": id
},
dataType: 'json',
success: function(response){
}
});
});
// function for Direction and Pointing of one Point-----------
function show_marker(Lng,Lat,date,In,Out,hname,hin,hout)
{
const marker = new mapboxgl.Marker({ "color": "#b40219" })
// const minPopup = new mapboxgl.Popup({closeButton: false, closeOnClick: false})
minPopup.setHTML("<strong><b>IN n OUT DATE:</b><br>"+date+"<br><b>IN n OUT TIME:</b><br>"+In+"-"+Out+"<br><b>HOTEL NAME:</b><br>"+hname+"<br><b>HOTEL IN n OUT:</b><br>"+hin+"-"+hout+"</strong>")
// marker.setPopup(minPopup)
marker.setLngLat([Lng,Lat])
// marker.setRotation(45);
marker.addTo(map)
}
const popup = new mapboxgl.Popup({ closeOnClick: false })
.setLngLat([-96, 37.8])
.setHTML('<h1>Hello World!</h1>')
.addTo(map);
</script>
You already have made addMarker function. You just have to pass the lat long there from your data collection. I am assuming that you are using the blade template only. In blade template, you can get your data to javascript variable easily.
var data = <?php echo json_encode($data); ?>
Then you have to parse encoded data into new variables using
var newData = JSON.parse(data);
After that, you can use your newData to get the lat long which you can pass in your function and use it.
var lat = newData[0].latitude
var lng = newData[0].longitude
const addMarker = (lat, lng) => {
const marker = new mapboxgl.Marker()
minPopup.setHTML("")
marker.setPopup(minPopup)
marker.setLngLat([lng,lat])
marker.addTo(map)
marker.togglePopup();
}
// calling add marker
addMarker(lat, lng);
Reference for passing data to javascript. Please note that these methods are different in different Laravel versions.

How to insert a link inside javascript (google maps)

I want to insert a link inside inside the JavaScript.
I want this link infoWindow.setContent('Adaugă sesizare pentru locația ta actuală .');
to send the user to add-sesizare.php?lat=&lng=&userid=
<?php include 'header.php';
session_start();
if (isset($_SESSION['user'])) {
$email = $_SESSION['user'];
$query = "SELECT * FROM useri WHERE email='$email' LIMIT 1";
$result = mysqli_query($con,$query);
$user = mysqli_fetch_assoc($result);
$userid = $user['id'];
} else { header('Location: login.php'); }
?>
<div class="head-first">
<div class="d-flex justify-content-between">
<a class="navbar-brand" href="#">
<i class="fas fa-users"></i> MyCity Curtici
</a>
<span style="font-size:30px;cursor:pointer;padding: 0 0 0 15px;" onclick="openNav()">☰</span>
</div>
</div>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
var user_id = "<?php echo $userid ?>";
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 46.35, lng: 21.3},
zoom: 15
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Adaugă sesizare pentru locația ta actuală .');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
google.maps.event.addListener(map, 'click', function(event) {
window.location='add-sesizare.php?lat='+event.latLng.lat()+'&long='+event.latLng.lng()+'&userid='+user_id;
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDd7JYEWDAJVdVkIzZOQumCHYbS2xsIvtM&callback=initMap"
async defer></script>
<?php include 'footer.php' ?>
You have an issue with your ' vs. ", and you don't have any attempt to add the local values of lat/lng returned by the geolocation service (which I assume is needed).
infoWindow.setContent('Adaugă sesizare pentru locația ta actuală .');
(uses ' for the javascript string, " for the quoting in HTML.)
proof of concept fiddle
code snippet:
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
var user_id = "$userid";
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 46.35,
lng: 21.3
},
zoom: 15
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Adaugă sesizare pentru locația ta actuală .');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
google.maps.event.addListener(map, 'click', function(event) {
window.location = 'add-sesizare.php?lat=' + event.latLng.lat() + '&long=' + event.latLng.lng() + '&userid=' + user_id;
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

Google map search by address

how can I search by location(address).
I want to pass the location to my map. Now I have added lat, long.
Or is there a quick way to find out the lat and long with javascript?
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.0000, -98.0000), Here I want to just add the location for example Dublin, Ireland
mapTypeId: google.maps.MapTypeId.ROADMAP
}
http://jsfiddle.net/pc7Uu/346
Thanks for your help.
Best
It is called Geocoding, it is actually very easy to use, read the The Google Maps Geocoding API to get started, since you are using JavaScript you don't need an API_KEY so you can actually convert addresses to lat/lng values with requests like this:
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
You will get a JSON with the coordinates inside the "location" key, like this:
...
"location" : {
"lat" : 37.4220352,
"lng" : -122.0841244
},
...
There are changes from V2 to V3 (recommended). Here are both documentations in case you want use an specific version:
V3 API: http://code.google.com/apis/maps/documentation/geocoding/
V2 API: http://code.google.com/apis/maps/documentation/services.html#Geocoding
If you want autocomplete functionality and/or site name to lat/lng coordinates, check the Place Autocomplete Hotel Search example.
Google Maps Geocoding API is intended for that purpose, the below example shows how to set map center based on the provided address:
//Data
var cities = [
{
city : 'Toronto',
desc : 'This is the best city in the world!',
lat : 43.7000,
long : -79.4000
},
{
city : 'New York',
desc : 'This city is aiiiiite!',
lat : 40.6700,
long : -73.9400
},
{
city : 'Chicago',
desc : 'This is the second best city in the world!',
lat : 41.8819,
long : -87.6278
},
{
city : 'Los Angeles',
desc : 'This city is live!',
lat : 34.0500,
long : -118.2500
},
{
city : 'Las Vegas',
desc : 'Sin City...\'nuff said!',
lat : 36.0800,
long : -115.1522
}
];
//Angular App Module and Controller
angular.module('mapsApp', [])
.controller('MapCtrl', function ($scope) {
var mapOptions = {
zoom: 4,
//center: new google.maps.LatLng(40.0000, -98.0000),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var setMapCenterByAddress = function(map,address) {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
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,
title: address
});
}
else {
console.log("Geocoding failed: " + status);
}
});
}
};
setMapCenterByAddress($scope.map,'Dublin, Ireland');
});
<script src="http://maps.googleapis.com/maps/api/js?key=&sensor=false"></script>
<script src="http://code.angularjs.org/1.2.25/angular.js"></script>
<script src="map.js"></script>
<style>
#map {
height:420px;
width:600px;
}
</style>
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div id="map"></div>
</div>
I think your present code won't do what you are trying to do.
First, here's what the code needs to do, in plain English. I will explain each part later.
1. Send a request to the Google Geocoding API : This request will include the address you are trying to find lat&lng for. You will receive a response in the form of JSON, which you will parse to get the information you need.
2. Save the information (latitude and longitude) in a variable
3. Create a map, and use the lat&lng you found above as its center.
Okay, now here are the sources for the code. Don't worry, these code samples are very straightforward and you will easily understand what to do.
How to send the 'GET' request:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
} else {
document.body.className = 'error';
}
}
};
request.open("GET", url , true);
request.send(null);
The http request for geocoding:
https://developers.google.com/maps/documentation/geocoding/intro#GeocodingRequests
Here is what the code will look like: (example)
var json = https://maps.googleapis.com/maps/api/geocode/json?address=1600+"ADD ADDRESS HERE"&key=YOUR_API_KEY;
var object = JSON.parse(json);
Then you can extract the lat&lng from this object.
After that, create a map using: (link) www.developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
(Use the latitude and longitude you extracted above as the 'center' of the google map you will create)
I used this plugin it is very simple:
https://ubilabs.github.io/geocomplete/
alternative free service of geo location to coordinates you can use openstreet map, you can combine this with jquery autocomplete
http://nominatim.openstreetmap.org/search/

MVC Controller getting hit twice on page load

My MVC Controller is getting hit twice on page load, and I am stumped on how to solve this problem.
I'm using navigator.geolocation.getCurrentPosition in my Layout page, and that passes the latitude and longitude to my controller.
I have RenderAction in a div, just in case the user has JavaScript disabled, as some people still do
:-(
This is what is causing my problem:
The RenderAction is getting rendered 1st and hitting the controller. Then, the AJAX request is firing and hitting the controller.
So my controller is getting hit twice per request.
Is there something I'm missing which will stop that, because at the moment, all I can think of is to remove the render action from the page.
Code:
<div class="dvWeather">
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
</div>
if (navigator.geolocation) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var aj = "gl";
$.ajax({
url: '#Url.Action("PvCurrentWeatherConditions", "Weather")',
type: 'get',
data: {
lat: lat,
lon: lon,
aj: aj
},
success: function (result) {
$('.dvWeather').html(result);
}
});
}
public PartialViewResult PvCurrentWeatherConditions(string lat, string lon, string aj)
{
if (Request.IsAjaxRequest())
{
try
{
//TODO create Viewmodel
GeoCoordinate gc = new GeoCoordinate();
var latitude = gc.Latitude = Convert.ToDouble(lat);
var longitude = gc.Longitude = Convert.ToDouble(lon);
string latlon = latitude + "," + longitude;
var displayCurrentConditions = _igcc.CurrentConditions(latlon);
return PartialView("pvCurrentWeatherConditions");
}
catch (FormatException)
{
//TODO get ip address
return PartialView("pvLocationBasedOnIpAddress");
}
catch (Exception)
{
return PartialView("pvError");
}
}
return PartialView("pvLocationBasedOnIpAddress");
}
Perhaps use another method for checking if the visitor has javascript disabled, like noscript:
<noscript>
<meta http-equiv="refresh" content="[URL]?java=off">
</noscript>
then handle the querystring in a new action.
You don't have to remove the Render action. Just make another (negative) check in the div:
<div class="dvWeather">
<script type="text/javascript>
//if (!navigator.geolocation) { : Edit
if (navigator.geolocation == null) {
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
}
</script>
</div>
Edit:
if (navigator.geolocation != null) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
This way only one call will be made.
Hope it helps.

Adding dynamic markers on to mapbox map file.

I am looking for a way to add markers on to a map which I have created in a web page... Here is the code for the page...
<link href='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.css' rel='stylesheet' />
<script src='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.js'></script>
<style>
#map {
width: 100%;
height: 600px;
}
</style>
<div id='map' />
<script type='text/javascript'>
var map = L.mapbox.map('map', '[mapname]')
</script>
This renders the map from mapbox - but I cannot figure out how to write a web service to provide the markers. This data is stored in a table in a SQL database.
I understand that I can load a GeoJSON file with the data in - but I am unsure on how to create this file - and how it differs from regular JSON - any help would be grateful!
Thanks
I don't know GeoJSON, but this is how you handle it using the Google Maps v3 API:
For one marker:
lng = (4.502384184313996, 4.461185453845246);
lat = (51.011527400014664, 51.02974935275779);
cur_loc = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: cur_loc, //To be defined with LatLng variable type
draggable: false,
animation: google.maps.Animation.DROP,
icon: image
});
// To add the marker to the map, call setMap();
marker.setMap(map);
For multiple markers retrieved from MySQL (Ajax):
google.maps.event.addListener(map, 'idle', function () {
var bounds = map.getBounds();
var ne_lat = bounds.getNorthEast().lat();
var ne_lng = bounds.getNorthEast().lng();
var sw_lat = bounds.getSouthWest().lat();
var sw_lng = bounds.getSouthWest().lng();
// Call you server with ajax passing it the bounds
$.ajax({
type: "GET",
url: "http://www.zwoop.be/develop/home/bars/bars_get_markers.php",
data: {
'ne_lat': ne_lat,
'ne_lng': ne_lng,
'sw_lat': sw_lat,
'sw_lng': sw_lng
},
datatype: "json",
success: function(data){
if(data){
// In the ajax callback delete the current markers and add new markers
function clearOverlays() {
for (var i = 0; i < array_markers.length; i++ ){
array_markers[i].setMap(null);
}
array_markers = [];
};
clearOverlays();
//parse the returned json obect
//Create a marker for each of the returned objects
var obj = $.parseJSON(data);
$.each(obj, function(index,el) {
var bar_position = new google.maps.LatLng(el.lat, el.lng);
image_bar = "http://www.sherv.net/cm/emoticons/drink/whiskey-smiley-emoticon.gif";
var marker = new google.maps.Marker({
position: bar_position,
map: map,
icon: image_bar
});
//Add info window. With HTML, the text format can be edited.
google.maps.event.addListener(marker, 'click', function() {
if (infowindow){
infowindow.close();
};
content = "<div id='infowindow_container'><h3><a class='profile_name_bar' href='#' id='" + el.profile_id + "'>"+el.profile_name+"</a></h3></div>";
infowindow = new google.maps.InfoWindow({
content: content
});
infowindow.open(map,marker);
});
array_markers.push(marker);
});
//Place the markers on the map
function setAllMap(map) {
for (var i = 0; i < array_markers.length; i++) {
array_markers[i].setMap(map);
}
}
setAllMap(map);
//marker clusterer
var zoom = 17;
var size = size ==-1?null:size;
var style = style ==-1?null:style;
var markerCluster = new MarkerClusterer(map, array_markers,{maxZoom:zoom,gridSize:size});
}
},
error: function (xhr, ajaxOptions, error) {
alert(error);
}
})
});
This code looks at the viewport of the map and loads the markers dynamically. When you zoom / pan, the code will query the database: the LatLng coordinates of the map bounds are sent to the server and the marker coordindates that are found in the database are returned from the Ajax call. The marker coordinates are loaded into an array at the client and written on the map.
I used the marker clusterer to avoid crowded markers.
I hope this helps. I don't know the benefits of the plugin that you are using though.
I'm doing something similar, this is where I'm up to.
I use PHP to get the coordinates from the MySQL database and return something like this:
var geoJson = [
{
type: 'Feature',
"geometry": { "type": "Point", "coordinates": [-77.03, 38.90]},
"properties": {}
},
{
type: 'Feature',
"geometry": { "type": "Point", "coordinates": [-64.567, 32.483]},
"properties": {}
}
];
The PHP file looks something like this:
<?php
// Connect
$link = mysqli_connect("[host]","[username]","[password]","[database-name]") or die("Error " . mysqli_error($link));
// Get the coordinates of the places
$query = "SELECT * FROM `places`";
$places = $link->query($query);
var geoJson = [<?php
// Loop through places and plot them on map
// This is just building the JSON string
$i = 1;
while($venue = $venues->fetch_assoc()):
if($i > 1){ echo ","; } ?>
{
type: 'Feature',
"geometry": { "type": "Point", "coordinates": [<?php echo $venue['lon']; ?>, <?php echo $venue['lat']; ?>]},
"properties": {}
}
<?php $i++; ?>
<?php endwhile; ?>
];
map.markerLayer.setGeoJSON(geoJson);
Note - This PHP is inside the Javascript that is making the map.
Like I said its early days for me as well. The code above works, but its just as far as I've got so far. The next thing I'm going to look at is JavaScript templates and using them to pull in the data that way. I have a feeling that will be a better way but I'm not sure. Anyway maybe that's useful to you, let me know if you get any further with it :)

Categories

Resources