show google map inside a jquery dialogue form - google-maps

Hi i'm trying to show a map in my form inside a jquery dialogue,
my jquery dialogue return a partial view where i put this code inside #section scripts and i called also the maps api
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
// Where all the fun happens
function Initialize() {
// Google has tweaked their interface somewhat - this tells the api to use that new UI
google.maps.visualRefresh = true;
var Liverpool = new google.maps.LatLng(53.408841, -2.981397);
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: Liverpool,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
// This makes the div with id "map_canvas" a google map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// This shows adding a simple pin "marker" - this happens to be the Tate Gallery in Liverpool!
var myLatlng = new google.maps.LatLng(53.40091, -2.994464);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Tate Gallery'
});
// You can make markers different colors... google it up!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
// a sample list of JSON encoded data of places to visit in Liverpool, UK
// you can either make up a JSON list server side, or call it from a controller using JSONResult
var data = [
{ "Id": 1, "PlaceName": "Liverpool Museum", "OpeningHours": "9-5, M-F", "GeoLong": "53.410146", "GeoLat": "-2.979919" },
{ "Id": 2, "PlaceName": "Merseyside Maritime Museum ", "OpeningHours": "9-1,2-5, M-F", "GeoLong": "53.401217", "GeoLat": "-2.993052" },
{ "Id": 3, "PlaceName": "Walker Art Gallery", "OpeningHours": "9-7, M-F", "GeoLong": "53.409839", "GeoLat": "-2.979447" },
{ "Id": 4, "PlaceName": "National Conservation Centre", "OpeningHours": "10-6, M-F", "GeoLong": "53.407511", "GeoLat": "-2.984683" }
];
// Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
$.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
});
// Make the marker-pin blue!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
// put in some information about each json object - in this case, the opening hours.
var infowindow = new google.maps.InfoWindow({
content: "<div class='infoDiv'><h2>" + item.PlaceName + "</h2>" + "<div><h4>Opening hours: " + item.OpeningHours + "</h4></div></div>"
});
// finally hook up an "OnClick" listener to the map so it pops up out info-window when the marker-pin is clicked!
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
})
}
i'm calling the map inside a div :
<div id="map_canvas" style="height: 240px; border: 1px solid gray"> map here</div>
but the problem that my map is not showing in the dialogue, even though it works well in normal page
any help plz !?

I've solved this issue with the following code:
this code is on the main view, the #next is a trigger of the form to submit, and the #dialog is inside the #form.
$(function () {
datepair();
$('#dialog').dialog({
autoOpen: false,
modal: true,
height: 720,
width: 700,
resizable: false,
title: 'Verify Location',
show: "fade",
hide: "fade",
open: function (event, ui) {
var form = $('#form');
$.ajax({
url: form.attr('actoin'),
type: form.attr('method'),
data: form.serialize(),
context: this,
success: function (result) {
$(this).html(result);
}
});
}
});
$('#next').click(function (e) {
$('#dialog').dialog('open');
return false;
});
});
this code is on the partialView
$(function () {
window.$required = $('<div></div>').dialog({
autoOpen: false,
resizable: false,
modal: true,
title: 'Verity Location Error',
buttons: {
"Ok": function () {
$(this).dialog('close');
callback();
}
}
});
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (json) {
Initialize();
}
});
return false;
});
function callback() {
$('#dialog').dialog('close');
}
function Initialize() {
//init the map
}
and this is the controller
public ActionResult PartialViewMapController()
{
return PartialView();
}
Hope it not to late for you :)

Related

how do I filter pins on Google Map pulled from a json api endpoint using Vue

I have a map with a number of pins on it, the pins are generated from an endpoint api (json). I want to filter the pins via an input that has a v-modal - the search criteria is already set up and is pulled from the same api.
Even if someone can give some tips as to where in the vue lifecycle the filter should happen, i.e mounted, updated computed ect
Originally I used this article as a reference
https://medium.com/#limichelle21/integrating-google-maps-api-for-multiple-locations-a4329517977a
created() {
axios
.get(
`https://cors-anywhere.herokuapp.com/myEndpoint`
)
.then(response => {
// JSON responses are automatically parsed.
this.allProperties = response.data;
this.markers = this.allProperties.map(function (x) {
return {
lat: parseFloat(x.lat).toFixed(3),
lng: parseFloat(x.lng).toFixed(3),
add: x.dispAddress,
propId: x.property_id,
propPrice: x.outputAskingPrice,
propImg: x.imagePath
};
});
this.allProperties = response.data.map(x => {
x.searchIndex = `${x.sellingStatus} ${x.priceType} ${x.typeNames[0]} ${x.typeNames[1]} ${x.dispAddress}`.toLowerCase();
return x;
});
});
},
mounted: function () {
var _this = this;
function initMap() {
var center = {
lat: 53,
lng: -3
};
var map = new google.maps.Map(document.getElementById("map-canvas"), {
zoom: 10,
center: center
});
var newPin = new google.maps.Marker({
position: center,
map: map
});
}
},
updated() {
var _this = this;
var map = new google.maps.Map(document.getElementById("map-canvas"), {
zoom: 9,
center: new window.google.maps.LatLng(55.961, -3)
});
var infowindow = new google.maps.InfoWindow({});
var newPin;
var count;
for (count = 0; count < _this.markers.length; count++) {
newPin = new google.maps.Marker({
position: new google.maps.LatLng(
_this.markers[count].lat,
_this.markers[count].lng
),
map: map,
icon: "../assets/img/map-pin.png"
});
google.maps.event.addListener(
newPin,
"click",
(function (newPin, count) {
return function () {
infowindow.setContent(` ${_this.markers[count].add} <p> ${_this.markers[count].propPrice}</p><img src="${_this.markers[count].propImg}"><p>`);
infowindow.open(map, newPin);
};
})(newPin, count)
);
}
If you have v-model on an <input> field like mentioned in your question, you are binding the value of this <input> field to a variable probably defined in the data part of your Vue component. The value is always up to date in the model (reactive binding). You can watch this value and then trigger a function which updates Google Maps. Here is an example:
Vue.component('demo', {
data () {
return {
inputField: ''
};
},
created () {
console.log('Component script loaded, HTML not yet ready, load the data from your backend. Use a flag like isLoading or similar to indicate when the data is ready to enable input.');
},
mounted () {
console.log('Component mounted, HTML rendered, load Google Maps');
},
watch: {
inputField (newValue) {
console.log(`inputField changed to ${newValue}. Trigger here a method which update Google Maps. Make sure to debounce the input here, so that it does not trigger a Google Maps update too often.`);
}
},
template: `
<div>
<input type="text" v-model="inputField" placeholder="Lookup place">
</div>`
});
new Vue({ el: '#vue-demo-container' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue-demo-container">
<demo></demo>
</div>

google maps api center on my location with a button

Everything is working but I would really like for the last button (GPS) (sorry can't post image)
to center the map on the user location instead of just refreshing the map like I currently have it set up to do.
An example of how this would work is for the user to have the webpage open and scroll around the map, possibly changing to satellite view, then be able to click the above button (or any button for that matter) and have the map pan back to their location. Not sure if this is even possible, but I can't seem to figure it out on my own. Any help is very much appreciated. Here is the link to my Frankenstein map. http://deepfrogphoto.com/Brett-Pelletier-Photography/Links/maps/wasatch-ski-map-mobile.htm
var map, GeoMarker;
function toggleLayer(this_layer){
if(this_layer.getMap()) {
this_layer.setMap(null)
} else {
this_layer.setMap(map);}}
function initialize() {
var mapOptions = {
zoom: 20,
center: new google.maps.LatLng(40.563855, -111.675426),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
layer1 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "skilines",
from: "1R5pCEyNN74N8Dt9MkfNXA6A9D1HbQESzOR1fYFa7",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer2 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "resorts",
from: "19iu58FDFcBIZZ-wU1iZcf89AI5ABDJ7YTv355su5",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer3 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "summerhiking",
from: "1t1XNnG7J7Zu1p5mIUpm6qIGVYwzhkCgPy_je0IKr",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer4 = new google.maps.KmlLayer('URL-to-KML.kml',
{
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
}
google.maps.event.addDomListener(window, 'load', initialize);
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');}
//]]>
</script>
<title>Wasatch Map by deepfrogphoto</title>
</head>
<body>
<b>Wasatch Map by deepfrogphoto -</b>
<form>
<button onclick="myFunction()">Center Map on My Location</button>
</form>
<div id="map_canvas"></div>
</body>
add a button with onclick event listener
<button onclick="myFunction()">Center</button>
then create the myFunction to center the map to user position
function myFunction(){
Map.panTo(UserCords);//UserCords = user current latitude, longitude. I suppose you have them!!!
}
EDIT
function myFunction(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(getPosition,showError);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function getPosition(position)
{
UserLatitude = position.coords.latitude;
UserLongitude = position.coords.longitude;
showPosition(UserLatitude, UserLongitude);
}
function showPosition(userLatitude, userLongitude){
lat= userLatitude;
lon= userLongitude;
latlon=new google.maps.LatLng(lat, lon);
YourMap.panTo(latlon);
}
function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.")
break;
case error.TIMEOUT:
alert("The request to get user location timed out.")
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.")
break;
}
}

How to add multiple markers on mobile Google Map and display the content when click?

hello i am working on the phonegap apps which can display the location markers on google map.
It is supposed to have a detail box pop up when i click on the marker, but it does not function.
can anyone help me to correct the code?
many thanks
var mobileDemo = { 'center': '57.7973333,12.0502107', 'zoom': 8 };
////////////////////////////////////////////////////////////
$('#basic_map').live('pageinit', function() {
demo.add('basic_map', function() {
$('#map_canvas').gmap({'center': mobileDemo.center, 'zoom': mobileDemo.zoom, 'disableDefaultUI':true,
'callback': function() {
var self = this;
self.addMarker({'position': this.get('map').getCenter() }).click(function() {
self.openInfoWindow({ 'content': 'Hello World!' }, this);
});
}});
$('#map_canvas').gmap('addMarker', { position: new google.maps.LatLng(57.9973333,12.0502107)})
.click(function() {
var self = this;
self.openInfoWindow({ 'content': 'Hello Worl23!' }, this);
} )
$('#map_canvas').gmap('addMarker', { position: new google.maps.LatLng(57.373333,12.0502107)})
.click(function() {
var self = this;
self.openInfoWindow({ 'content': 'Hello Worl234!' }, this);
} )
}).load('basic_map');
});
$('#basic_map').live('pageshow', function() {
demo.add('basic_map', function() { $('#map_canvas').gmap('refresh'); }).load('basic_map');
});
</script>
There is a easier way to use Google Maps api,https://github.com/HPNeo/gmaps. And what you need almost like this,http://hpneo.github.com/gmaps/examples/markers.html, you click the marker and the detail info shows

Google Maps API. Center and zoom

$('#map_canvas').gmap().bind('init', function(ev, map) {
if (myPosition) {
$('#map_canvas').gmap({ 'center' : myPosition });
$('#map_canvas').gmap('addMarker', { 'position': myPosition, 'bounds': true, 'icon' : '../../css/images/current_location.png'}).click( function () {
$('#map_canvas').gmap('openInfoWindow', { 'content': 'You are here!' }, this);
});
$('#map_canvas').gmap('option', 'zoom', 20);
} else {
$('#map_canvas').gmap('option', 'zoom', 8);
}
$.each(markers, function(i, marker) {
$('#map_canvas').gmap('addMarker', {
'position': new google.maps.LatLng(marker.lat, marker.lng),
'bounds': true
}).click(function() {
$('#map_canvas').gmap('openInfoWindow', { 'content': marker.name }, this);
});
});
});
I want to center and zoom to specific position. The result of this piece of code: http://postimage.org
Add the latLng of each marker to a LatLngBounds object, then use fitBounds()
Here is an example.
All in all I reached my purpose, but fitBounds() function did some mess to my expectation. My task was: create lot of makers and place them in the map. If I was use fitBounds() function my map zooms out to fit all my markers. Now how does look like my map: http://postimage.org

jquery-ui-map load json and update markers

I've searched all over the web and SO, but I couldn't figure this out.
Here's the problem:
I'm using the below demo from jquery-ui-map site to load a JSON file:
http://jquery-ui-map.googlecode.com/svn/trunk/demos/jquery-google-maps-json.html
It works fine to load my markers, but I need to refresh its content every 30 seconds and grab new markers.
At first I thought I would just call the function again, but that left the markers there. After some research I found out I needed to clear the markers (not so easy on V3, but I was able to to do) but the issue is that I can't get the markers to show again.
If I use the destroy function, then I'm able to reload new markers and remove the old ones, but that causes the map to blink. When I try to clear markers then no new markers are shown.
Any help is greatly appreciated.
Below is my code:
<script type="text/javascript">
function mapTest() {
$('#map_canvas').gmap('destroy');
//clearMap();
demo.add(function() {
$('#map_canvas').gmap({'disableDefaultUI':true, 'callback': function() {
var self = this;
$.getJSON( 'json/demo.json?'+ new Date().getTime(), function(data) {
$.each( data.markers, function(i, marker) {
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
});
});
});
}});
}).load();
}
function clearMap(){
$('#map_canvas').gmap('clear', 'markers');
}
mapTest();
setInterval(mapTest, 30000 );
</script>
Cheers.
Your map initialization function is inside the mapTest() function - which you call over an over again every 30 seconds with setInterval.
That is wrong, because you are essentially reloading the map( you destroy it and then recreate it again every 30 seconds ), and that is why it blinks.
Place the map initialization outside the mapTest(), but clear and retrieve new markers from within the mapTest()
Update:
var mapOptions = {
disableDefaultUI: true
// add more options if you wish.
};
function mapTest() {
$('#map_canvas').gmap('clear', 'markers'); // clear old markers
$.getJSON( 'json/demo.json?'+ new Date().getTime(), function(data) {
$.each( data.markers, function(i, marker) {
var self = this;
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
});
});
});
}
$(function(){
$('#map_canvas').gmap(mapOptions, function(){
$.getJSON( 'json/demo.json?'+ new Date().getTime(), function(data) {
$.each( data.markers, function(i, marker) {
var self = this;
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
});
});
});
});
setInterval(mapTest, 30000 );
});
I found a Solution to update markers without reloading the map. Try this code...
$(document).ready(function() {
var $map = $('#map_canvas');
App.drawMap($map);
setInterval(function() {
$('#map_canvas').gmap('clear', 'markers');
App.drawMap($map);
},10000);
});
var App = {
drawMap: function($divMap) {
Http.doAjaxGetJson('../../js/testjson.json', function(data) {
for (var k in data.gpsData) {
$divMap.gmap({ 'center': new google.maps.LatLng(data.gpsData[k].latitude,data.gpsData[k].longitude),'zoom':15, 'callback': function() {}});
$divMap.gmap('addMarker', {
'title':data.obj.name,
'position': new google.maps.LatLng(data.gpsData[k].latitude, data.gpsData[k].longitude),
'bounds': false,
}).click(function() {
var $_obj = $(this);
});
}
});
}
};
By this code markers will update in every 10 seconds..