MVC ActionLink in google.maps.InfoWindow - javascript

I have a problem with JavaScript code
$.getJSON('#Url.Action("GetData", "Home")', function (data) {
$.each(data, function (i, item) {
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
'map': map,
'title': item.PlaceName
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
var infowindow = new google.maps.InfoWindow({
content: '#Html.ActionLink("Details","Details",new { id= '+item.Id+'})'
});
How to pass Id to controller using #Html.ActionLink?
In the controller I have a POST version of the Index method. How do I pass the Id using the ActionLink in this method?
In View I try to take ViewBag but nothing is displayed
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(int id)
{
ViewBag.id = id;
return RedirectToAction("Index", "Home");
}
EDIT:
Code of my View:
#{
ViewBag.Title = "Home Page";
}
Id : #ViewBag.id
<script src="http://maps.google.com/maps/api/js? key=**********" type="text/javascript"></script>
<style>
.stationInfo {
height: 150px;
width: 250px;
}
</style>
<div id="canvas" style="height: 600px; width:600px;"></div>
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
GetMap();
});
function GetMap() {
google.maps.visualRefresh = true;
var Moscow = new google.maps.LatLng(55.752622, 37.617567);
var mapOptions = {
zoom: 15,
center: Moscow,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
var map = new google.maps.Map(document.getElementById("canvas"), mapOptions);
var myLatlng = new google.maps.LatLng(55.752622, 37.617567);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Name'
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png')
$.getJSON('#Url.Action("GetData", "Home")', function (data) {керы
$.each(data, function (i, item) {
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
'map': map,
'title': item.PlaceName
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
var infowindow = new google.maps.InfoWindow({
content:
'<form action="#Url.Action("Index", "Home")" method="POST">' +
'<input type="hidden" name="id"/>' +
'<a class="f" href="#" data-id="' + item.Id + '">Details</a></form>'
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
})
});
$(function () {
$(document).on("click", "a.f", function (e) {
e.preventDefault();
var v = $(this).data("id");
var f = $(this).closest("form");
f.find("[name='id']").val(v);
f.submit();
});
});
}
</script>
}
But when I click on the link after the redirect ViewBag is empty(

you can't pass param from javascript to razor. but you can try to inject the id to the link after he is been generated :
var link = '#Html.Action("Details","Details")'+'/'+item.id;
var infowindow = new google.maps.InfoWindow({
content: 'details'
});
for the updated questio try to do this :
[HttpPost]
public ActionResult Index(int id)
{
ViewBag.id = id;
return Index();
}

It does not work that way because your loop executes on the client side and your server code (Html.ActionLink call) executes way before that in the server.
What you can do is, Use the Url.Action method to generate the path without the route values and append that with your dynamic variable.
This should work.
var infowindow = new google.maps.InfoWindow({
content: 'Details'
});
Replace Home with your controller name where you have the Details action method is available.
EDIT : As per the comment
In the controller I have a POST version of the Index method. How do I
pass the Id ?
If you do not prefer to pass the value in the querystring in GET request, but prefer a form post, you can submit a form. Build a form element for each item with a hidden input with name attribute value set to "Id" (same as your action method parameter name). You may keep the Id value in html5 data attribute which you will read later.
var infowindow = new google.maps.InfoWindow({
content: '<form action="#Url.Action("Index", "Home")" method="POST">' +
'<input type="hidden" name="id"/>' +
'<a class="f" href="#" data-id="' + item.Id + '">Details</a></form>'
});
Now we need a little javascript to hijack the normal link click behavior. When user clicks the link, we need to read the data attribute value we set (the Id value) and set that as the hidden input field value and submit the form.
$(function(){
$(document).on("click","a.f",function(e) {
e.preventDefault();
var v = $(this).data("id");
var f = $(this).closest("form");
f.find("[name='id']").val(v);
f.submit();
});
});

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.

Passing php var to javascript in Laravel

I am trying to pass php $var to Javascript in google map script. I have address table in DB. And with controller I fetch it to view and now try to pass it in Javascript and iterate it.
But having some trouble I think my code a bit corrupted. By the way I dont have lat and lng, just addresses.
function initMap(){
var options = {
zoom:8,
center:
#foreach($address as $addr){
{!! $addr->address !!}
}
#endforeach
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
#foreach($address as $addr){
{!! $addr->address !!}
}
#endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
})
}
And Map API calling
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY-KEY&callback=initMap"></script>
controller
public function index()
{
$address = DB::table("allestates")
->get();
return view("home", compact('address'));
}
Address column in DB:
I see a few things that could be causing the issue
Try this:
function initMap(){
var options = {
zoom:8,
center:
'{!! $address[0]->address !!}'
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
#foreach($address as $addr)
'{!! $addr->address !!}'
#endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
})
}
So first of all the #foreach (...) does not use { or }
Second you want to output any information that is not only numeric inside of quotes
Hope this helps

Pass PHP variable to javascript to show location of IP on Google Maps [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here on the same page U am using the php code to return an ip of domain and I would like to pass this php $ip variable to the below javascript code, in the button tag. How can I pass this php $ip variable into the below javascript code.
Here is the php submit part, without google maps:
<form method="post" action="">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit']))
{
$ip = gethostbyname($_POST['name']);
echo $ip;
}
?>
Here is the javascript code in this code: I would like to pass above php $ip variable
I would like to remove the input tag and button tag in this javascript code because their existing two input and submit button tags on the single page
My goal in this project is to lookup the location of the IP and show it on google maps.
<script type="text/javascript">
$(function(){
try{
IPMapper.initializeMap("map");
//IPMapper.addIPMarker("111.111.111.111");
} catch(e){
//handle error
}
});
</script>
<input id="ip" name="ip" type="text" />
<button onclick="IPMapper.addIPMarker($('#ip').val());">Geocode</button>
<div id="map" style="height: 500px;width:500px; ">
</div>
For reference: the IPMapper code in javascript
/*!
* IP Address geocoding API for Google Maps
* http://lab.abhinayrathore.com/ipmapper/
* Last Updated: June 13, 2012
*/
var IPMapper = {
map: null,
mapTypeId: google.maps.MapTypeId.ROADMAP,
latlngbound: null,
infowindow: null,
baseUrl: "http://freegeoip.net/json/",
initializeMap: function(mapId){
IPMapper.latlngbound = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(0, 0);
//set Map options
var mapOptions = {
zoom: 1,
center: latlng,
mapTypeId: IPMapper.mapTypeId
}
//init Map
IPMapper.map = new google.maps.Map(document.getElementById(mapId), mapOptions);
//init info window
IPMapper.infowindow = new google.maps.InfoWindow();
//info window close event
google.maps.event.addListener(IPMapper.infowindow, 'closeclick',
function() {
IPMapper.map.fitBounds(IPMapper.latlngbound);
IPMapper.map.panToBounds(IPMapper.latlngbound);
});
},
addIPArray: function(ipArray){
ipArray = IPMapper.uniqueArray(ipArray); //get unique array elements
//add Map Marker for each IP
for (var i = 0; i < ipArray.length; i++){
IPMapper.addIPMarker(ipArray[i]);
}
},
addIPMarker: function(ip){
ipRegex = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
if($.trim(ip) != '' && ipRegex.test(ip)){ //validate IP Address format
var url = encodeURI(IPMapper.baseUrl + ip + "?callback=?"); //geocoding url
$.getJSON(url, function(data) { //get Geocoded JSONP data
if($.trim(data.latitude) != '' && data.latitude != '0' && !isNaN(data.latitude)){ //Geocoding successfull
var latitude = data.latitude;
var longitude = data.longitude;
var contentString = "";
$.each(data, function(key, val) {
contentString += '<b>' + key.toUpperCase().replace("_", " ") + ':</b> ' + val + '<br />';
});
var latlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({ //create Map Marker
map: IPMapper.map,
draggable: false,
position: latlng
});
IPMapper.placeIPMarker(marker, latlng, contentString); //place Marker on Map
} else {
IPMapper.logError('IP Address geocoding failed!');
$.error('IP Address geocoding failed!');
}
});
} else {
IPMapper.logError('Invalid IP Address!');
$.error('Invalid IP Address!');
}
},
placeIPMarker: function(marker, latlng, contentString){ //place Marker on Map
marker.setPosition(latlng);
google.maps.event.addListener(marker, 'click', function() {
IPMapper.getIPInfoWindowEvent(marker, contentString);
});
IPMapper.latlngbound.extend(latlng);
IPMapper.map.setCenter(IPMapper.latlngbound.getCenter());
IPMapper.map.fitBounds(IPMapper.latlngbound);
},
getIPInfoWindowEvent: function(marker, contentString){ //open Marker Info Window
IPMapper.infowindow.close()
IPMapper.infowindow.setContent(contentString);
IPMapper.infowindow.open(IPMapper.map, marker);
},
uniqueArray: function(inputArray){ //return unique elements from Array
var a = [];
for(var i=0; i<inputArray.length; i++) {
for(var j=i+1; j<inputArray.length; j++) {
if (inputArray[i] === inputArray[j]) j = ++i;
}
a.push(inputArray[i]);
}
return a;
},
logError: function(error){
if (typeof console == 'object') { console.error(error); }
}
}
Maybe...
<button onclick="IPMapper.addIPMarker($('<?php echo $ip ?>').val());">Geocode</button>
Not an expert on javascript
A better solution would be to add the data to the element and use an event listener.
<button data-ip-marker="<?= htmlspecialchars($ip) ?>">Geocode</button>
and in JavaScript
$(document).on('click', '[data-ip-marker]', function() {
var marker = $('#' + this.getAttribute('data-ip-marker'));
if (marker.length) {
IPMapper.addIPMarker(marker.val());
}
});

Update db with latitude and longitude when google map marker point is move

Well, I've a google map where all lat and long comes from db and it's showing on the map.
What I can do with this map:
1) I can create new point after right click on the map,
2) I can delete existing point.
Now can you plz tell me how can i update the db with new lat and long when the existing marker point is move to another place ?
you can see my live map on www.creativeartbd.com/map
Index.php page code:
<!DOCTYPE html>
<html>
<head>
<title>Google Map</title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api
/js?sensor=false"></script>
<script type="text/javascript">
$(document).ready(function() {
var mapCenter = new google.maps.LatLng(23.721869, 90.390518); //Google map
Coordinates
var map;
map_initialize(); // initialize google map
//############### Google Map Initialize ##############
function map_initialize()
{
var googleMapOptions =
{
center: mapCenter, // map center
zoom: 15, //zoom level, 0 = earth view to higher value
maxZoom: 15,
minZoom: 5,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL //zoom control size
},
scaleControl: true, // enable scale control
mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
};
map = new google.maps.Map(document.getElementById("google_map"),
googleMapOptions);
//Load Markers from the XML File, Check (map_process.php)
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>'+ $(this).attr('address') +'</p>';
var type = $(this).attr('type');
var point = new
google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));
create_marker(point, name, address, false, false, false, "icons/pin_blue.png");
});
});
//Right Click to Drop a New Marker
google.maps.event.addListener(map, 'rightclick', function(event) {
//Edit form to be displayed with new marker
var EditForm = '<p><div class="marker-edit">'+
'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">'+
'<label for="pName"><span>Place Name :</span><input type="text" name="pName"
class="save-name" placeholder="Enter Title" maxlength="40" /></label>'+
'<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc"
placeholder="Enter Address" maxlength="150"></textarea></label>'+
'<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option
value="restaurant">Rastaurant</option><option value="bar">Bar</option>'+
'<option value="house">House</option></select></label>'+
'</form>'+
'</div></p><button name="save-marker" class="save-marker">Save Marker
Details</button>';
//Drop a new Marker with our Edit Form
create_marker(event.latLng, 'New Marker', EditForm, true, true, true,
"icons/pin_green.png");
});
}
//############### Create Marker Function ##############
function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble,
Removable, iconPath)
{
//new marker
var marker = new google.maps.Marker({
position: MapPos,
map: map,
draggable:true,
animation: google.maps.Animation.DROP,
title:"Hello World!",
icon: iconPath
});
//Content structure of info Window for the Markers
var contentString = $('<div class="marker-info-win">'+
'<div class="marker-inner-win"><span class="info-content">'+
'<h1 class="marker-heading">'+MapTitle+'</h1>'+
MapDesc+
'</span><button name="remove-marker" class="remove-marker" title="Remove
Marker">Remove Marker</button>'+
'</div></div>');
//Create an infoWindow
var infowindow = new google.maps.InfoWindow();
//set the content of infoWindow
infowindow.setContent(contentString[0]);
//Find remove button in infoWindow
var removeBtn = contentString.find('button.remove-marker')[0];
var saveBtn = contentString.find('button.save-marker')[0];
//add click listner to remove marker button
google.maps.event.addDomListener(removeBtn, "click", function(event) {
remove_marker(marker);
});
if(typeof saveBtn !== 'undefined') //continue only when save button is present
{
//add click listner to save marker button
google.maps.event.addDomListener(saveBtn, "click", function(event)
{
var mReplace = contentString.find('span.info-content');
//html to be replaced after success
var mName = contentString.find('input.save-name')[0].value; //name input field value
var mDesc = contentString.find('textarea.save-desc')[0].value; //description input
field value
var mType = contentString.find('select.save-type')[0].value; //type of marker
if(mName =='' || mDesc =='')
{
alert("Please enter Name and Description!");
}else{
save_marker(marker, mName, mDesc, mType,
mReplace); //call save marker function
}
});
}
//add click listner to save marker button
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker); // click on marker opens info window
});
if(InfoOpenDefault) //whether info window should be open by default
{
infowindow.open(map,marker);
}
}
//############### Remove Marker Function ##############
function remove_marker(Marker)
{
/* determine whether marker is draggable
new markers are draggable and saved markers are fixed */
//Remove saved marker from DB and map using jQuery Ajax
var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
var myData = {del : 'true', latlang : mLatLang}; //post variables
$.ajax({
type: "POST",
url: "map_process.php",
data: myData,
success:function(data){
Marker.setMap(null);
alert(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
}
//############### Save Marker Function ##############
function save_marker(Marker, mName, mAddress, mType, replaceWin)
{
//Save new marker using jQuery Ajax
var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
var myData = {name : mName, address : mAddress, latlang : mLatLang, type :
mType }; //post variables
console.log(replaceWin);
$.ajax({
type: "POST",
url: "map_process.php",
data: myData,
success:function(data){
replaceWin.html(data); //replace info window with new html
Marker.setDraggable(true); //set marker to fixed
Marker.setIcon('icons/pin_blue.png'); //replace icon
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
}
});
</script>
</head>
<body>
<h1 class="heading">My Google Map</h1>
<div align="center">Right Click to Drop a New Marker</div>
<div id="google_map"></div>
</body>
</html>
Map_process.php code
// database settings
$db_username = 'username';
$db_password = 'pass';
$db_name = 'db';
$db_host = 'my host';
//mysqli
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno())
{
header('HTTP/1.1 500 Error: Could not connect to db!');
exit();
}
################ Save & delete markers #################
if($_POST) //run only if there's a post data
{
//make sure request is comming from Ajax
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr){
header('HTTP/1.1 500 Error: Request must come from Ajax!');
exit();
}
// get marker position and split it for database
$mLatLang = explode(',',$_POST["latlang"]);
$mLat = filter_var($mLatLang[0], FILTER_VALIDATE_FLOAT);
$mLng = filter_var($mLatLang[1], FILTER_VALIDATE_FLOAT);
//Delete Marker
if(isset($_POST["del"]) && $_POST["del"]==true)
{
$results = $mysqli->query("DELETE FROM markers WHERE lat=$mLat AND lng=$mLng");
if (!$results) {
header('HTTP/1.1 500 Error: Could not delete Markers!');
exit();
}
exit("Done!");
}
$mName = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$mAddress = filter_var($_POST["address"], FILTER_SANITIZE_STRING);
$mType = filter_var($_POST["type"], FILTER_SANITIZE_STRING);
$results = $mysqli->query("INSERT INTO markers (name, address, lat, lng, type)
VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType')");
if (!$results) {
header('HTTP/1.1 500 Error: Could not create marker!');
exit();
}
$output = '<h1 class="marker-heading">'.$mName.'</h1><p>'.$mAddress.'</p>';
exit($output);
}
################ Continue generating Map XML #################
//Create a new DOMDocument object
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers"); //Create new element node
$parnode = $dom->appendChild($node); //make the node show up
// Select all the rows in the markers table
$results = $mysqli->query("SELECT * FROM markers WHERE 1");
if (!$results) {
header('HTTP/1.1 500 Error: Could not get markers!');
exit();
}
//set document header to text/xml
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while($obj = $results->fetch_object())
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$obj->name);
$newnode->setAttribute("address", $obj->address);
$newnode->setAttribute("lat", $obj->lat);
$newnode->setAttribute("lng", $obj->lng);
$newnode->setAttribute("type", $obj->type);
}
echo $dom->saveXML();
Thanks a ton for you help :)
You should add an even listener to the marker that is fired when the marker is dropped.
// adds an event listener on the marker.
// The event is fired when the marker is dropped in this case
google.maps.event.addListener(marker, 'dragend', function() {
alert('Marker dropped');
});
Don't forget to set the marker option draggable:true
Here is the doc for the methods and events for the Marker class: google.maps.Marker
And here a demo on jsFiddle

Calling Javascript function

Extending a website I didn't build. I want to be able to call the ShowWindow proc with a parameter. How would I do that? New to JQuery and Javascript.
default.aspx
<script type="text/javascript" src="/scripts/jquery-1.2.6.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a#ShowWindow').click(function() {
window.open("TerminalInfo.aspx?", 'Info', 'scrollbars=yes,width=510,height=536');
})
});
default.aspx.cs
Building the aspx dynamically...
public static string ToHtml(this Location location)
{
var html = new StringBuilder();
html.Append("<td><a href='#' id='ShowWindow'>ShowLetter</a></td>"); //This works
html.Append("<td><a href='#' id='ShowWindow(\"MyInfo.aspx\")'>Read More</a></td>"); //How can I do this? It doesn't work.
return html.ToString();
}
public static string ToHtml(this Location location)
{
var html = new StringBuilder();
html.Append("<td><a href='MyInfo.aspx' id='ShowWindow'>Read More</a></td>");
return html.ToString();
}
and then
$('a#ShowWindow').click(function(e) {
window.open($(this).attr("href"), 'Info', 'scrollbars=yes,width=510,height=536');
e.preventDefault();
})
It's a little different approach but it degrades better if JavaScript is unavailable.
Update (to work on several links in table)
$('table a').click(function(e) {
window.open($(e.target).attr("href"), 'Info', 'scrollbars=yes,width=510,height=536');
e.preventDefault();
});
var strattonn = {};
strattonn.openWindow = function(url, title) {
window.open(url, title, 'scrollbars=yes,width=510,height=536');
return false;
}
public static string ToHtml(this Location location)
{
var html = new StringBuilder();
html.Append("<td><a href='#' onclick='return strattonn.openWindow('MyInfo.aspx', 'My Info')'>Read More</a></td>");
return html.ToString();
}

Categories

Resources