how to center a google map based on user location - javascript

I have this script that call posts as markers into a Google Maps:
<?php
$args = array( 'post_type' => 'braiders', 'posts_per_page' => -1 );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ): ?>
<!-- WordPress has found matching posts -->
<div class="results-main-content">
<div class="results-group-items">
<?php $i = 1; ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if ( get_post_meta($post->ID, 'martygeocoderlatlng', true) !== '' ) : ?>
<div class="result-list-items">
<div class="results-left">
<?php
if ( has_post_thumbnail() ) {
// Get the post thumbnail URL
$feat_image = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
?>
<a href="<?php the_permalink(); ?>"><div class="result-items-image" style="background-image: url(<?php echo $feat_image; ?>);">
<p><?php the_title(); ?>
</p>
</div>
</a>
<?php } ?>
<!-- .result-items-image -->
</div>
<!-- results-left -->
<div class="result-right">
<?php the_content(); ?>
</div>
<!-- result-right -->
</div>
<!-- result-list-items -->
<?php endif; ?>
<?php $i++; ?>
<?php endwhile; ?>
</div>
<!-- results-group-items -->
</div>
<!-- .results-main-content -->
<script type="text/javascript">
var locations = [
<?php $i = 1; while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if ( get_post_meta($post->ID, 'martygeocoderlatlng', true) !== '' ) : ?> {
latlng: new google.maps.LatLng <?php echo get_post_meta($post->ID, 'martygeocoderlatlng', true); ?>,
info: document.getElementById( 'item<?php echo $i; ?>' )
},
<?php endif; ?>
<?php $i++; endwhile; ?>
];
</script>
and this next script that displays the map based on manually coded latlng:
var infowindow = new google.maps.InfoWindow();
var pinkmarker = new google.maps.MarkerImage('/wp- content/themes/halfempty/pink_Marker.png', new google.maps.Size(18, 32) );
var shadow = new google.maps.MarkerImage('/wp- content/themes/halfempty/shadow.png', new google.maps.Size(37, 34) );
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(35.1495343, -90.0489801),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: locations[i].latlng,
icon: pinkmarker,
shadow: shadow,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].info);
infowindow.open(map, marker);
}
})(marker, i));
}
}
I would like to know how to alter the above .js script that centers the Google to actually center the map based on user location when they access the page through their browser?
All I know is I need to dynamically pull the latlng of the visitor/user instead of manually coding it.
Thank you for taking a crack at it.

You can use the following script:
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
user_location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(user_location);
});
} else {
/* Browser doesn't support Geolocation */
}
Caveat: Some browsers do not support this without SSL. As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.
Your code should now look like this:
var infowindow = new google.maps.InfoWindow();
var pinkmarker = new google.maps.MarkerImage('/wp- content/themes/halfempty/pink_Marker.png', new google.maps.Size(18, 32) );
var shadow = new google.maps.MarkerImage('/wp- content/themes/halfempty/shadow.png', new google.maps.Size(37, 34) );
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(35.1495343, -90.0489801),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: locations[i].latlng,
icon: pinkmarker,
shadow: shadow,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].info);
infowindow.open(map, marker);
}
})(marker, i));
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
user_location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(user_location);
});
} else {
/* Browser doesn't support Geolocation */
}
}

Related

Why are my custom Google Maps icons showing in pc-browsers, but not in Android browsers?

I have a website with a Google Map on it. This is a Wordpress-site, and each (custom) post on the site has some geographical location meta values, generated through an Advanced Custom Fields' Maps-field.
I have created five custom icons, which are hosted on the same server as the website. The icons to be shown on the map then differs based on another custom value for each post. There are in total appr. 180 markers to be shown simultaneously.
When viewing the rendered map with a computer the custom icons loads as expected.
However, if I view the same page with an Android phone, the custom icons are ignored, and the default red marker(s) loads instead. Why is this?
Update:
Additional info:
It works as expected on my older Android tablet! It does not work on my phone.
The tablet is a Samsung SM-T525 running on Android 4.4.2.
The phone is a Huawei P9 running on Android 7.0.
This is the javascript I am using:
(function($) {
function render_map($el) {
var $markers = $el.find('.marker');
var args = {
zoom: 16,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($el[0], args);
map.markers = [];
$markers.each(function() {
add_marker($(this), map);
});
center_map(map);
}
function add_marker($marker, map) {
var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));
var icon = $marker.attr('data-icon');
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon
});
map.markers.push(marker);
if ($marker.html()) {
var infowindow = new google.maps.InfoWindow({
content: $marker.html()
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}
function center_map(map) {
var bounds = new google.maps.LatLngBounds();
$.each(map.markers, function(i, marker) {
var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
bounds.extend(latlng);
});
if (map.markers.length == 1) {
map.setCenter(bounds.getCenter());
map.setZoom(16);
} else {
map.fitBounds(bounds);
}
}
$(document).ready(function() {
$('.acf-map').each(function() {
render_map($(this));
});
});
})(jQuery);
This is the relevant php:
$args = array(
'post_type' => 'customposttype',
'posts_per_page' => -1,
'post_status' => 'publish',
'no_found_rows' => true
);
$mapquery = new WP_Query( $args );
if( $mapquery->have_posts()): ?>
<div class="acf-map" style="height:708px;">
<?php
while ($mapquery->have_posts()): $mapquery->the_post();
$personalmap = get_field( 'personalmap' );
$status = get_field( 'status' );
switch ($status) {
case "variant-one":
$markertype = 'https://example.com/wp-content/uploads/custommarker-one.png';
break;
case "variant-two":
$markertype = 'https://example.com/wp-content/uploads/custommarker-two.png';
break;
case "variant-three":
$markertype = 'https://example.com/wp-content/uploads/custommarker-three.png';
break;
case "variant-four":
$markertype = 'https://example.com/wp-content/uploads/custommarker-four.png';
break;
case "variant-five":
$markertype = 'https://example.com/wp-content/uploads/custommarker-five.png';
break;
default:
$markertype = 'https://example.com/wp-content/uploads/custommarker-one.png';
} ?>
<div class="marker" data-lat="<?php echo $personalmap['lat']; ?>" data-lng="<?php echo $personalmap['lng']; ?> "data-icon="<?php echo $markertype; ?>"></div>
<?php
endwhile; ?>
</div>
<?php
endif;
wp_reset_postdata();
-And then it suddenly works. WHY I have no idea! (That is: Why it didn't work (on Android phones) in the first place is beyond my knowlegde...)
I did do some changes though, but I don't understand why they effected this issue.
Javascript:
(function($) {
function render_map($el) {
var $markers = $el.find('.marker');
var args = {
zoom: 16,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($el[0], args);
map.markers = [];
$markers.each(function() {
add_marker($(this), map);
});
center_map(map);
}
function add_marker($marker, map) {
var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));
var icon = $marker.attr('data-icon');
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon
});
map.markers.push(marker);
if ($marker.html()) {
var infowindow = new google.maps.InfoWindow({
content: $marker.html(),
maxWidth: 350 // This is added
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(map, 'click', function() { //This is added
infowindow.close();
});
}
}
function center_map(map) {
var bounds = new google.maps.LatLngBounds();
$.each(map.markers, function(i, marker) {
var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
bounds.extend(latlng);
});
if (map.markers.length == 1) {
map.setCenter(bounds.getCenter());
map.setZoom(16);
} else {
map.fitBounds(bounds);
}
}
$(document).ready(function() {
$('.acf-map').each(function() {
render_map($(this));
});
});
})(jQuery);
The php:
$args = array(
'post_type' => 'customposttype',
'posts_per_page' => -1,
'post_status' => 'publish',
'no_found_rows' => true
);
$mapquery = new WP_Query( $args );
if( $mapquery->have_posts()): ?>
<div class="acf-map" style="height:708px;">
<?php
while ($mapquery->have_posts()): $mapquery->the_post();
$personalmap = get_field( 'personalmap' );
$status = get_post_meta(get_the_ID(),'status', 'true'); //This has changed
switch ($status) {
case "variant-one":
$markertype = 'https://example.com/wp-content/uploads/custommarker-one.png';
break;
case "variant-two":
$markertype = 'https://example.com/wp-content/uploads/custommarker-two.png';
break;
case "variant-three":
$markertype = 'https://example.com/wp-content/uploads/custommarker-three.png';
break;
case "variant-four":
$markertype = 'https://example.com/wp-content/uploads/custommarker-four.png';
break;
case "variant-five":
$markertype = 'https://example.com/wp-content/uploads/custommarker-five.png';
break;
default:
$markertype = 'https://example.com/wp-content/uploads/custommarker-one.png';
} ?>
<div class="marker" data-lat="<?php echo $personalmap['lat']; ?>" data-lng="<?php echo $personalmap['lng']; ?> "data-icon="<?php echo $markertype; ?>">
<div class="mapinfo">
<div class="mapinfo-title">
<h3><?php the_title(); ?></h3>
</div>
<div class="mapinfo-content">
<img src="<?php the_field('logo'); ?>" alt="<?php the_title(); ?>" height="83" width="83">
<p><strong><?php the_field('some_value'); ?> texy <?php the_field('smoe_other_value'); ?></strong></p>
</div>
</div>
</div>
<?php
endwhile; ?>
</div>
<?php
endif;
wp_reset_postdata();

Only load 10 markers from database

I have a question. I make a project using google maps. i put 30 data on database. but when i wanna show the marker on the map, it only load for 10 data. also when I filter my data based on the category, it load for 10 data only. I check inspact element on my browser (im using mozilla) and found this error : "SyntaxError: unterminated string literal" what does it means?
Here's my code to show markers & map on the web :
<?php
$title = "Peta Masjid";
include_once "header.php";
?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-info panel-dashboard centered">
<div class="panel-heading">
<h2 class="panel-title"><strong> <?php echo $title ?> </strong></h2>
</div>
<div class="panel-body">
<div id="map" style="width:100%;height:380px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyAbXF62gVyhJOVkRiTHcVp_BkjPYDQfH5w">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-6.966667, 110.416664),
disableDefaultUI: true
};
var mapElement = document.getElementById('map');
var map = new google.maps.Map(mapElement, mapOptions);
setMarkers(map, officeLocations);
}
var officeLocations = [
<?php
$data = file_get_contents('http://localhost:8082/sig/getdata.php');
$no=1;
if(json_decode($data,true)){
$obj = json_decode($data);
foreach($obj->results as $item){
?>
['<?php echo $item->id_masjid ?>','<?php echo $item->nama_masjid ?>','<?php echo $item->alamat ?>', '<?php echo $item->longitude ?>', '<?php echo $item->latitude ?>','<?php echo $item->gambar ?>'],
<?php
}
}
?>
];
function setMarkers(map, locations)
{
var globalPin = 'img/tanda.png';
for (var i = 0; i < locations.length; i++) {
var office = locations[i];
var myLatLng = new google.maps.LatLng(office[4], office[3]);
var infowindow = new google.maps.InfoWindow({content: contentString});
var contentString =
'<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h5 id="firstHeading" class="firstHeading">'+ office[1] + '</h5>'+
'<div id="bodyContent">'+
'<p>' + office[2] + '</p>' +
'<p><img src="img/'+office[5]+'" style="width:50%;height:190px;" /></p>' +
'<p><a href=detail.php?id='+office[0]+'>Info Detail</p></a>'+
'</div>'+
'</div>';
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: office[1],
icon:'img/tanda.png'
});
google.maps.event.addListener(marker, 'click', getInfoCallback(map, contentString));
}
}
function getInfoCallback(map, content) {
var infowindow = new google.maps.InfoWindow({content: content});
return function() {
infowindow.setContent(content);
infowindow.open(map, this);
};
}
initialize();
</script>
</div>
</div></div></div>
</div>
</div>
<?php include_once "footer.php"; ?>
And here's code to get data from database (getdata.php)
<?php
include "connection.php";
$Q = mysql_query("SELECT * FROM mosques WHERE category = 'Mushola'")or die(mysql_error());
if($Q){
$posts = array();
if(mysql_num_rows($Q))
{
while($post = mysql_fetch_assoc($Q)){
$posts[] = $post;
}
}
$data = json_encode(array('results'=>$posts));
echo $data;
}
?>
You can use a counter in your while loop that counts to ten and then breaks the loop or an if statement than only runs if the counter is not 10
-Aron DC

How to set a cusctom multi-marker on maps API v3 codeigniter

I have a problem with custom marker in codeigniter.
var locations =
[
<?php if(isset($kop)) : ?>
<?php foreach($kop->result() as $item) : ?>
<?php
switch ($item->kop_jop) {
case '1':
$image = "http://localhost/kop/assets/icon/hospital.png";
break;
case '2':
$image = "http://localhost/kop/assets/icon/beach.png";
break;
}
?>
['<div class="media"><div class="media-left"><img style="width:125px; height:90px;" class="media-object" src="<?= base_url(); ?>assets/images/<?= $item->kop_gambar;?>" alt="..."></div><div class="media-body"><h4 class="media-heading"><?= $item->kop_nama ;?><br><p style="font-size:12px;color: #767676;"><div class="addr"><?= $item->kop_alamat;?></div><div id="maker"><?= $image;?></div><div id="lat"><?= $item->kop_latitude;?></div><div id="lng"><?= $item->kop_longitude;?></div></p></h4><?= substr($item->kop_deskripsi, 0, 80);?><br><div id="more_detail"><h5>Rute | <a target="_blank" href="<?= base_url()."detail_kop/" . $item->id_kop; ?>">Detail</a></h5></div></div></div>',<?php echo $item->kop_latitude;?>, <?php echo $item->kop_longitude;?>, <?= echo $image;?>],
<?php endforeach; ?>
<?php endif; ?>
];
SET VIEW
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: location[i][3],
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
You just need to add a condition on the loop when you're adding Markers
Note - this is just a pseudocode
...
if (var i=0; i<array.length; i++){
var image = "[default]";
if (array[i].kop_jop == 1){
image = "http://localhost/kop/assets/icon/hospital.png";
} else {
image = "http: //localhost/kop/assets/icon/beach.png";
}
var marker = new google.maps.Marker({
position: {lat: array[i].lat, lng: array[i].lng},
map: map,
icon: image
});
}
...
More information about setting Markers can be found here

Google Maps Marker Content in box

I get the Coordinates and the Names and "ID" out of an MySQL Table but why is in every Marker the same Text an also the same link ?
Why is the text not different ???
It show only the last ID but it should add after every element in the data base an other marker !
The markers are at the right Position and the "Content" is in the Source Code also right but not at the markes why ?!
Please Help
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(51.124213, 10.60936),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new
google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var contentString;
var elementeInArray = 0;
var LatLngList = new Array;
<? php
$i = 1;
foreach($FertigID as $ID) {
$result = mysql_query("SELECT * FROM Daten_CH WHERE Objektnummer = ".$ID.
"");
while ($Ergebnisse = mysql_fetch_array($result)) {
// Werden alle ergebnisse (ID´s) in einen Array geschriebenn
echo $$Ergebnisse["Objektnummer"];
if (isset($Ergebnisse["Gis_y"]) && $Ergebnisse["Gis_y"] != "" &&
$Ergebnisse["Gis_y"] != " ") {
echo $i; ?>
// MARKER TEXT
contentString = '<?php echo $i; ?> </br><?php echo
$Ergebnisse["Objektname"]; ?>
</br><a href="Change.php?ID=<?php echo $ID; ?>">
<input type="button" value="BEARBEITEN"></button></a>';
var Position = new google.maps.LatLng( <? php echo $Ergebnisse["Gis_y"]; ?> , <? php echo $Ergebnisse["Gis_x"]; ?> );
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker <? php echo $i; ?> = new google.maps.Marker({
position: Position,
map: map,
title: '<?php echo $Ergebnisse["AA_Objektname"]; ?>'
});
google.maps.event.addListener(marker <? php echo $i; ?> , 'click', function () {
infowindow.open(map, marker <? php echo $i; ?> );
});
LatLngList[elementeInArray] = new google.maps.LatLng( <? php echo $Ergebnisse["Gis_y"]; ?> , <? php echo $Ergebnisse["Gis_x"]; ?> );
elementeInArray++;
<? php
}
}
$i++;
}
?>
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend(LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds(bounds);
var opt = {
minZoom: 1,
maxZoom: 12
};
map.setOptions(opt);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Because you should assign the contentString to the marker, and update the infowindow with each markers assigned content instead. As it is now, the only contentString available is the last created. Furthermore, you really dont have to create multiple numbered markers. You just need one marker reference only.
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: Position,
map: map,
content: contenString, // <-- assign content to the marker itself
title: '<?php echo $Ergebnisse["AA_Objektname"]; ?>'
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.content);
infowindow.open(map, this);
});
This would do the trick.

Google Maps API V3 - Element onClick - Center Map / Open InfoWindow

I've been playing around with the Google Maps API lately, and I have links that perform a JS function. This JS function partially works, on click it centers the map to the pin coords, but I also want it to show the infowindow; Everything works except opening the infowindow. Any help would be amazing! the code is a little cluttered with PHP / WP functions.
<script type="text/javascript">
var map;
var infowindow;
var marker;
function initialize() {
var styles = [
{
stylers: [
{ hue: "#c09c3d" },
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 50 },
{ visibility: "simplified" }
]
}
];
infowindow = new google.maps.InfoWindow({
maxWidth: 275
});
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(<?php echo $centerCoords; ?>),
styles: styles,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var image = '<?php echo get_template_directory_uri(); ?>/images/icon_marker.png';
var locations = [
<?php
// LOOP ARGUMENTS
$args = array( 'post_type' => 'cbd_dealers', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC' ); // -1 Shows ALL Posts
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
// CUSTOM CONTENT
$dealerStreetAddress = get_post_meta($post->ID,"dealerStreetAddress",true);
$dealerCity = get_post_meta($post->ID,"dealerCity",true);
$dealerState = get_post_meta($post->ID,"dealerState",true);
$dealerZipCode = get_post_meta($post->ID,"dealerZipCode",true);
$dealerCoords = get_post_meta($post->ID,"dealerCoords",true);
$dealerPhoneNumber = get_post_meta($post->ID,"dealerPhoneNumber",true);
$dealerLink = get_post_meta($post->ID,"dealerLink",true);
?>
{
latlng : new google.maps.LatLng<?php echo $dealerCoords; ?>,
info: '<style>a{color:#000000 !important;}a:hover{color:#DCB54F !important;}</style><strong style="line-height:25px;display:block;width:230px;"><?php the_title(); ?></strong><?php echo $dealerStreetAddress; ?><br /><?php echo $dealerCity; ?>, <?php echo $dealerState; ?> <?php echo $dealerZipCode; ?><br /><?php echo $dealerPhoneNumber; ?><br />View Website'
},
<?php /* END WHILE AND RESET QUERY */ endwhile; wp_reset_query(); ?>
];
for (var i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: locations[i].latlng,
icon: image,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].info);
infowindow.open(map, marker);
}
})(marker, i));
}
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' + 'callback=initialize';
document.body.appendChild(script);
}
function set_map_center(lat, lng) {
var myLatLng = new google.maps.LatLng(lat, lng);
infowindow.open(map,marker);
map.setCenter(myLatLng);
map.setZoom(12);
infowindow.open(map, marker);
}
window.onload = loadScript;
</script>
Thanks to Suvi's comment, i understand better.
First off, you will need to store all of your markers in an array when you create them. Then in your set_map_center function, you can scan through the markers to find a matching Lat/Lng, and then trigger that marker's click event.
To trigger the marker click event:
google.maps.event.trigger(markers[i], 'click');
Here is how I check for a lat/lng match
function set_map_center(lat, lng){
var pos = new google.maps.LatLng(lat, lng)
for(var i=0;i<markers.length;i++){
if(markers[i].position.equals(pos))
google.maps.event.trigger(markers[i], 'click');
}
}
JSFiddle Example

Categories

Resources